The easiest way would be to use a library like this one and specifically you want noStrings
to be true
export class CustomValidator{ // Number only validation
static numeric(control: AbstractControl) {
let val = control.value;
const hasError = validate({val: val}, {val: {numericality: {noStrings: true}}});
if (hasError) return null;
return val;
}
}
Slack has a cool way of making tabs small viewport friendly on some of their admin pages. I made something similar using bootstrap. It's kind of a tabs ? dropdown.
Demo: http://jsbin.com/nowuyi/1
Here's what it looks like on a big viewport:
Here's how it looks collapsed on a small viewport:
Here's how it looks expanded on a small viewport:
the HTML is exactly the same as default bootstrap tabs.
There is a small JS snippet, which requires jquery (and inserts two span elements into the DOM):
$.fn.responsiveTabs = function() {
this.addClass('responsive-tabs');
this.append($('<span class="glyphicon glyphicon-triangle-bottom"></span>'));
this.append($('<span class="glyphicon glyphicon-triangle-top"></span>'));
this.on('click', 'li.active > a, span.glyphicon', function() {
this.toggleClass('open');
}.bind(this));
this.on('click', 'li:not(.active) > a', function() {
this.removeClass('open');
}.bind(this));
};
$('.nav.nav-tabs').responsiveTabs();
And then there is a lot of css (less):
@xs: 768px;
.responsive-tabs.nav-tabs {
position: relative;
z-index: 10;
height: 42px;
overflow: visible;
border-bottom: none;
@media(min-width: @xs) {
border-bottom: 1px solid #ddd;
}
span.glyphicon {
position: absolute;
top: 14px;
right: 22px;
&.glyphicon-triangle-top {
display: none;
}
@media(min-width: @xs) {
display: none;
}
}
> li {
display: none;
float: none;
text-align: center;
&:last-of-type > a {
margin-right: 0;
}
> a {
margin-right: 0;
background: #fff;
border: 1px solid #DDDDDD;
@media(min-width: @xs) {
margin-right: 4px;
}
}
&.active {
display: block;
a {
@media(min-width: @xs) {
border-bottom-color: transparent;
}
border: 1px solid #DDDDDD;
border-radius: 2px;
}
}
@media(min-width: @xs) {
display: block;
float: left;
}
}
&.open {
span.glyphicon {
&.glyphicon-triangle-top {
display: block;
@media(min-width: @xs) {
display: none;
}
}
&.glyphicon-triangle-bottom {
display: none;
}
}
> li {
display: block;
a {
border-radius: 0;
}
&:first-of-type a {
border-radius: 2px 2px 0 0;
}
&:last-of-type a {
border-radius: 0 0 2px 2px;
}
}
}
}
Another option that worked for me is playing with the dpi option of knitr::include_graphics()
like this:
```{r}
knitr::include_graphics("path/to/image.png", dpi = 100)
```
... which sure (unless you do the math) is trial and error compared to defining dimensions in the chunk, but maybe it will help somebody.
I know that this may not be a popular answer but I do agree with @Randy Minder on using third party tool when more complex comparison is needed.
This specific case here is easy and for this case such tools are not needed but this can get complex easily if you introduce more columns, databases on two servers, more complex comparison criteria and such.
There are a lot of these tools such as ApexSQL Data Diff or Quest Toad and you can always use them in trial mode to get the job done.
For me the issue was the IP address that charles was telling me to route to in my proxy settings was incorrect. To solve I ended up going to ifconfig
in the terminal and the trying the different IP addresses (listed next to inet
) at port 8888
for the current active connections
Lambda expressions are a simpler syntax for anonymous delegates and can be used everywhere an anonymous delegate can be used. However, the opposite is not true; lambda expressions can be converted to expression trees which allows for a lot of the magic like LINQ to SQL.
The following is an example of a LINQ to Objects expression using anonymous delegates then lambda expressions to show how much easier on the eye they are:
// anonymous delegate
var evens = Enumerable
.Range(1, 100)
.Where(delegate(int x) { return (x % 2) == 0; })
.ToList();
// lambda expression
var evens = Enumerable
.Range(1, 100)
.Where(x => (x % 2) == 0)
.ToList();
Lambda expressions and anonymous delegates have an advantage over writing a separate function: they implement closures which can allow you to pass local state to the function without adding parameters to the function or creating one-time-use objects.
Expression trees are a very powerful new feature of C# 3.0 that allow an API to look at the structure of an expression instead of just getting a reference to a method that can be executed. An API just has to make a delegate parameter into an Expression<T>
parameter and the compiler will generate an expression tree from a lambda instead of an anonymous delegate:
void Example(Predicate<int> aDelegate);
called like:
Example(x => x > 5);
becomes:
void Example(Expression<Predicate<int>> expressionTree);
The latter will get passed a representation of the abstract syntax tree that describes the expression x > 5
. LINQ to SQL relies on this behavior to be able to turn C# expressions in to the SQL expressions desired for filtering / ordering / etc. on the server side.
Java code:
public class MapActivity extends FragmentActivity implements LocationListener {
GoogleMap googleMap;
LatLng myPosition;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
// Getting reference to the SupportMapFragment of activity_main.xml
SupportMapFragment fm = (SupportMapFragment)
getSupportFragmentManager().findFragmentById(R.id.map);
// Getting GoogleMap object from the fragment
googleMap = fm.getMap();
// Enabling MyLocation Layer of Google Map
googleMap.setMyLocationEnabled(true);
// Getting LocationManager object from System Service LOCATION_SERVICE
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Creating a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Getting the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Getting Current Location
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
// Getting latitude of the current location
double latitude = location.getLatitude();
// Getting longitude of the current location
double longitude = location.getLongitude();
// Creating a LatLng object for the current location
LatLng latLng = new LatLng(latitude, longitude);
myPosition = new LatLng(latitude, longitude);
googleMap.addMarker(new MarkerOptions().position(myPosition).title("Start"));
}
}
}
activity_map.xml:
<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
android:id="@+id/map"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
class="com.google.android.gms.maps.SupportMapFragment"/>
You will get your current location in a blue circle.
Check this: http://en.wikipedia.org/wiki/Pigeonhole_principle. If A, B and C are of same type, it cannot be done. If A and B are 16-bit integers, and C is 32-bit, then you can simply use shifting.
The very nature of hashing algorithms is that they cannot provide a unique hash for each different input.
Perl string match can also be used for a simple yes/no.
my @foo=("hello", "world", "foo", "bar");
if ("@foo" =~ /\bhello\b/){
print "found";
}
else{
print "not found";
}
Check the following example:
// First get your image
$imgPath = 'path-to-your-picture/image.jpg';
$img = base64_encode(file_get_contents($imgPath));
echo '<img width="100" height="100" src="data:image/jpg;base64,'. $img .'" />'
Setup https://docs.djangoproject.com/en/dev/topics/logging/ and then these error's will echo where you point them. By default they tend to go off in the weeds so I always start off with a good logging setup before anything else.
Here is a really good example for a basic setup: https://ian.pizza/b/2013/04/16/getting-started-with-django-logging-in-5-minutes/
Edit: The new link is moved to: https://github.com/ianalexander/ianalexander/blob/master/content/blog/getting-started-with-django-logging-in-5-minutes.html
I'd like to point out that one issues is what if the same resources are in multiple jar files. Let's say you want to read /org/node/foo.txt, but not from one file, but from each and every jar file.
I have run into this same issue several times before. I was hoping in JDK 7 that someone would write a classpath filesystem, but alas not yet.
Spring has the Resource class which allows you to load classpath resources quite nicely.
I wrote a little prototype to solve this very problem of reading resources form multiple jar files. The prototype does not handle every edge case, but it does handle looking for resources in directories that are in the jar files.
I have used Stack Overflow for quite sometime. This is the second answer that I remember answering a question so forgive me if I go too long (it is my nature).
This is a prototype resource reader. The prototype is devoid of robust error checking.
I have two prototype jar files that I have setup.
<pre>
<dependency>
<groupId>invoke</groupId>
<artifactId>invoke</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>node</groupId>
<artifactId>node</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
The jar files each have a file under /org/node/ called resource.txt.
This is just a prototype of what a handler would look like with classpath:// I also have a resource.foo.txt in my local resources for this project.
It picks them all up and prints them out.
package com.foo;
import java.io.File;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URI;
import java.net.URL;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
/**
* Prototype resource reader.
* This prototype is devoid of error checking.
*
*
* I have two prototype jar files that I have setup.
* <pre>
* <dependency>
* <groupId>invoke</groupId>
* <artifactId>invoke</artifactId>
* <version>1.0-SNAPSHOT</version>
* </dependency>
*
* <dependency>
* <groupId>node</groupId>
* <artifactId>node</artifactId>
* <version>1.0-SNAPSHOT</version>
* </dependency>
* </pre>
* The jar files each have a file under /org/node/ called resource.txt.
* <br />
* This is just a prototype of what a handler would look like with classpath://
* I also have a resource.foo.txt in my local resources for this project.
* <br />
*/
public class ClasspathReader {
public static void main(String[] args) throws Exception {
/* This project includes two jar files that each have a resource located
in /org/node/ called resource.txt.
*/
/*
Name space is just a device I am using to see if a file in a dir
starts with a name space. Think of namespace like a file extension
but it is the start of the file not the end.
*/
String namespace = "resource";
//someResource is classpath.
String someResource = args.length > 0 ? args[0] :
//"classpath:///org/node/resource.txt"; It works with files
"classpath:///org/node/"; //It also works with directories
URI someResourceURI = URI.create(someResource);
System.out.println("URI of resource = " + someResourceURI);
someResource = someResourceURI.getPath();
System.out.println("PATH of resource =" + someResource);
boolean isDir = !someResource.endsWith(".txt");
/** Classpath resource can never really start with a starting slash.
* Logically they do, but in reality you have to strip it.
* This is a known behavior of classpath resources.
* It works with a slash unless the resource is in a jar file.
* Bottom line, by stripping it, it always works.
*/
if (someResource.startsWith("/")) {
someResource = someResource.substring(1);
}
/* Use the ClassLoader to lookup all resources that have this name.
Look for all resources that match the location we are looking for. */
Enumeration resources = null;
/* Check the context classloader first. Always use this if available. */
try {
resources =
Thread.currentThread().getContextClassLoader().getResources(someResource);
} catch (Exception ex) {
ex.printStackTrace();
}
if (resources == null || !resources.hasMoreElements()) {
resources = ClasspathReader.class.getClassLoader().getResources(someResource);
}
//Now iterate over the URLs of the resources from the classpath
while (resources.hasMoreElements()) {
URL resource = resources.nextElement();
/* if the resource is a file, it just means that we can use normal mechanism
to scan the directory.
*/
if (resource.getProtocol().equals("file")) {
//if it is a file then we can handle it the normal way.
handleFile(resource, namespace);
continue;
}
System.out.println("Resource " + resource);
/*
Split up the string that looks like this:
jar:file:/Users/rick/.m2/repository/invoke/invoke/1.0-SNAPSHOT/invoke-1.0-SNAPSHOT.jar!/org/node/
into
this /Users/rick/.m2/repository/invoke/invoke/1.0-SNAPSHOT/invoke-1.0-SNAPSHOT.jar
and this
/org/node/
*/
String[] split = resource.toString().split(":");
String[] split2 = split[2].split("!");
String zipFileName = split2[0];
String sresource = split2[1];
System.out.printf("After split zip file name = %s," +
" \nresource in zip %s \n", zipFileName, sresource);
/* Open up the zip file. */
ZipFile zipFile = new ZipFile(zipFileName);
/* Iterate through the entries. */
Enumeration entries = zipFile.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = entries.nextElement();
/* If it is a directory, then skip it. */
if (entry.isDirectory()) {
continue;
}
String entryName = entry.getName();
System.out.printf("zip entry name %s \n", entryName);
/* If it does not start with our someResource String
then it is not our resource so continue.
*/
if (!entryName.startsWith(someResource)) {
continue;
}
/* the fileName part from the entry name.
* where /foo/bar/foo/bee/bar.txt, bar.txt is the file
*/
String fileName = entryName.substring(entryName.lastIndexOf("/") + 1);
System.out.printf("fileName %s \n", fileName);
/* See if the file starts with our namespace and ends with our extension.
*/
if (fileName.startsWith(namespace) && fileName.endsWith(".txt")) {
/* If you found the file, print out
the contents fo the file to System.out.*/
try (Reader reader = new InputStreamReader(zipFile.getInputStream(entry))) {
StringBuilder builder = new StringBuilder();
int ch = 0;
while ((ch = reader.read()) != -1) {
builder.append((char) ch);
}
System.out.printf("zip fileName = %s\n\n####\n contents of file %s\n###\n", entryName, builder);
} catch (Exception ex) {
ex.printStackTrace();
}
}
//use the entry to see if it's the file '1.txt'
//Read from the byte using file.getInputStream(entry)
}
}
}
/**
* The file was on the file system not a zip file,
* this is here for completeness for this example.
* otherwise.
*
* @param resource
* @param namespace
* @throws Exception
*/
private static void handleFile(URL resource, String namespace) throws Exception {
System.out.println("Handle this resource as a file " + resource);
URI uri = resource.toURI();
File file = new File(uri.getPath());
if (file.isDirectory()) {
for (File childFile : file.listFiles()) {
if (childFile.isDirectory()) {
continue;
}
String fileName = childFile.getName();
if (fileName.startsWith(namespace) && fileName.endsWith("txt")) {
try (FileReader reader = new FileReader(childFile)) {
StringBuilder builder = new StringBuilder();
int ch = 0;
while ((ch = reader.read()) != -1) {
builder.append((char) ch);
}
System.out.printf("fileName = %s\n\n####\n contents of file %s\n###\n", childFile, builder);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
} else {
String fileName = file.getName();
if (fileName.startsWith(namespace) && fileName.endsWith("txt")) {
try (FileReader reader = new FileReader(file)) {
StringBuilder builder = new StringBuilder();
int ch = 0;
while ((ch = reader.read()) != -1) {
builder.append((char) ch);
}
System.out.printf("fileName = %s\n\n####\n contents of file %s\n###\n", fileName, builder);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
}
Use Range("A1").Text
instead of .Value
post comment edit:
Why?
Because the .Text
property of Range object returns what is literally visible in the spreadsheet, so if you cell displays for example i100l:25he*_92
then <- Text
will return exactly what it in the cell including any formatting.
The .Value
and .Value2
properties return what's stored in the cell under the hood excluding formatting. Specially .Value2
for date types, it will return the decimal representation.
If you want to dig deeper into the meaning and performance, I just found this article
which seems like a good guide
another edit
Here you go @Santosh
type in (MANUALLY) the values from the DEFAULT (col A) to other columns
Do not format column A at all
Format column B as Text
Format column C as Date[dd/mm/yyyy]
Format column D as Percentage
now,
paste this code in a module
Sub main()
Dim ws As Worksheet, i&, j&
Set ws = Sheets(1)
For i = 3 To 7
For j = 1 To 4
Debug.Print _
"row " & i & vbTab & vbTab & _
Cells(i, j).Text & vbTab & _
Cells(i, j).Value & vbTab & _
Cells(i, j).Value2
Next j
Next i
End Sub
and Analyse
the output! Its really easy and there isn't much more i can do to help :)
.TEXT .VALUE .VALUE2
row 3 hello hello hello
row 3 hello hello hello
row 3 hello hello hello
row 3 hello hello hello
row 4 1 1 1
row 4 1 1 1
row 4 01/01/1900 31/12/1899 1
row 4 1.00% 0.01 0.01
row 5 helo1$$ helo1$$ helo1$$
row 5 helo1$$ helo1$$ helo1$$
row 5 helo1$$ helo1$$ helo1$$
row 5 helo1$$ helo1$$ helo1$$
row 6 63 63 63
row 6 =7*9 =7*9 =7*9
row 6 03/03/1900 03/03/1900 63
row 6 6300.00% 63 63
row 7 29/05/2013 29/05/2013 41423
row 7 29/05/2013 29/05/2013 29/05/2013
row 7 29/05/2013 29/05/2013 41423
row 7 29/05/2013% 29/05/2013% 29/05/2013%
Can anyone give me a good example of when CROSS APPLY makes a difference in those cases where INNER JOIN will work as well?
See the article in my blog for detailed performance comparison:
CROSS APPLY
works better on things that have no simple JOIN
condition.
This one selects 3
last records from t2
for each record from t1
:
SELECT t1.*, t2o.*
FROM t1
CROSS APPLY
(
SELECT TOP 3 *
FROM t2
WHERE t2.t1_id = t1.id
ORDER BY
t2.rank DESC
) t2o
It cannot be easily formulated with an INNER JOIN
condition.
You could probably do something like that using CTE
's and window function:
WITH t2o AS
(
SELECT t2.*, ROW_NUMBER() OVER (PARTITION BY t1_id ORDER BY rank) AS rn
FROM t2
)
SELECT t1.*, t2o.*
FROM t1
INNER JOIN
t2o
ON t2o.t1_id = t1.id
AND t2o.rn <= 3
, but this is less readable and probably less efficient.
Update:
Just checked.
master
is a table of about 20,000,000
records with a PRIMARY KEY
on id
.
This query:
WITH q AS
(
SELECT *, ROW_NUMBER() OVER (ORDER BY id) AS rn
FROM master
),
t AS
(
SELECT 1 AS id
UNION ALL
SELECT 2
)
SELECT *
FROM t
JOIN q
ON q.rn <= t.id
runs for almost 30
seconds, while this one:
WITH t AS
(
SELECT 1 AS id
UNION ALL
SELECT 2
)
SELECT *
FROM t
CROSS APPLY
(
SELECT TOP (t.id) m.*
FROM master m
ORDER BY
id
) q
is instant.
Typically, I'll set the line-height
to be 200px. Usually does the trick.
You could insert both the key,value pair and its inverse into your map structure, but would have to convert the Integer to a string:
map.put("theKey", "theValue");
map.put("theValue", "theKey");
Using map.get("theValue") will then return "theKey".
It's a quick and dirty way that I've made constant maps, which will only work for a select few datasets:
If you want to keep <Integer, String>
you could maintain a second <String, Integer>
map to "put" the value -> key pairs.
For Swift 4 and higher that is a good way:
let attributsBold = [NSAttributedString.Key.font : UIFont.systemFont(ofSize: 16, weight: .bold)]
let attributsNormal = [NSAttributedString.Key.font : UIFont.systemFont(ofSize: 16, weight: .regular)]
var attributedString = NSMutableAttributedString(string: "Hi ", attributes:attributsNormal)
let boldStringPart = NSMutableAttributedString(string: "John", attributes:attributsBold)
attributedString.append(boldStringPart)
yourLabel.attributedText = attributedString
In the Label the Text looks like: "Hi John"
Response.Write("<scrip" + "t>test(" + x + "," + y + ");</script>");
breaking up the script keyword because VStudio / asp.net compiler doesn't like it
One good system is Basic4Android - great for anyone familiar with Basic,
You can use a tool like the TrIDNet - File Identifier to look for the Magic Number and other telltales, if the file format is in it's database it may tell you what it is for.
However searching the definitions did not turn up anything for the string "FLDB", but it checks more than magic numbers so it is worth a try.
If you are using Linux File is a command that will do a similar task.
The other thing to try is if you have access to the program that generated this file, there may be DLL's or EXE's from the database software that may contain meta information about the dll's creator which could give you a starting point for looking for software that can read the file outside of the program that originally created the .db
file.
Any click event before for update /edit/delete records message box alerts the user and if "Ok" proceed for the action else "cancel" remain unchanged. For this code no need to right separate java script code. it works for me
<a asp-action="Delete" asp-route-ID="@Item.ArtistID" onclick = "return confirm('Are you sure you wish to remove this Artist?');">Delete</a>
Try http://loadimpact.com the best I have found so far, but no alternative to it I can find.
EDIT:
Task has Wait method, Task.Wait(), which waits for the "promise" to resolve and then continues, thus rendering it synchronous. example:
async Task<String> MyAsyncMethod() { ... }
String mySyncMethod() {
return MyAsyncMethod().Wait();
}
BTW, if you set globals in MySQL:
SET GLOBAL sql_mode = 'NO_ENGINE_SUBSTITUTION';
SET SESSION sql_mode = 'NO_ENGINE_SUBSTITUTION';
This will not set it PERMANENTLY, and it will revert after every restart.
So you should set this in your config file (e.g. /etc/mysql/my.cnf
in the [mysqld] section), so that the changes remain in effect after MySQL restart:
Config File: /etc/mysql/my.cnf
[mysqld]
sql_mode = NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES
UPDATE: Newer versions of Mysql (e.g. 5.7.8 or above) may require slightly different syntax:
[mysqld]
sql-mode="STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION"
Make sure that there is a dash between sql-mode
not an underscore, and that modes are in double quotes.
Always reference the MySQL Docs for your version to see the sql-mode options.
Use Thread.sleep(long millis)
.
Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers. The thread does not lose ownership of any monitors.
One minute would be (60*1000) = 60000
milliseconds.
For example, this loop will print the current time once every 5 seconds:
try {
while (true) {
System.out.println(new Date());
Thread.sleep(5 * 1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
If your sleep period becomes too large for int
, explicitly compute in long
(e.g. 1000L
).
Oh, just with this:
$ docker-compose up client server database
Try:
while(scanf("%15s", words) != EOF)
You need to compare scanf
output with EOF
Since you are specifying a width of 15
in the format string, you'll read at most 15 char. So the words char array should be of size 16
( 15 +1
for null
char). So declare it as:
char words[16];
You could use getdate() in a default as this SO question's accepted answer shows. This way you don't provide the date, you just insert the rest and that date is the default value for the column.
You could also provide it in the values list of your insert and do it manually if you wish.
This is not an answer to your question but I believe it is the solution to your problem. The interface org.springframework.data.repository.CrudRepository
does indeed have methods that return java.lang.Iterable
but you should not use this interface. Instead use sub interfaces, in your case org.springframework.data.mongodb.repository.MongoRepository
. This interface has methods that return objects of type java.util.List
.
An update for iOS 6 : using auto-layout, even though you still can't set the UITextField's height from the Size Inspector in the Interface Builder (as of Xcode 4.5 DP4 at least), it is now possible to set a Height constraint on it, which you can edit from the Interface Builder.
Also, if you're setting the frame's height by code, auto-layout may reset it depending on the other constraints your view may have.
SELECT *
FROM TABLE_NAME
WHERE Date_Column >= DATEADD(MONTH, -3, GETDATE())
Mureinik's suggested method will return the same results, but doing it this way your query can benefit from any indexes on Date_Column
.
or you can check against last 90 days.
SELECT *
FROM TABLE_NAME
WHERE Date_Column >= DATEADD(DAY, -90, GETDATE())
I think you want to lowercase the checked value? Try:
var jIsHasKids = $('#chkIsHasKids:checked').val().toLowerCase();
or you want to check it, then get its value as lowercase:
var jIsHasKids = $('#chkIsHasKids').attr("checked", true).val().toLowerCase();
For windows you can use:
Running Windows command prompt commands in python.
import os
os.system('tzutil /s "Central Standard Time"')
In windows command prompt try:
This gives current timezone:
tzutil /g
This gives a list of timezones:
tzutil /l
This will set the timezone:
tzutil /s "Central America Standard Time"
For further reference: http://woshub.com/how-to-set-timezone-from-command-prompt-in-windows/
Try putting this HTML snippet into your served document:
<img id="ItemPreview" src="">
Then, on JavaScript side, you can dynamically modify image's src
attribute with so-called Data URL.
document.getElementById("ItemPreview").src = "data:image/png;base64," + yourByteArrayAsBase64;
Alternatively, using jQuery:
$('#ItemPreview').attr('src', `data:image/png;base64,${yourByteArrayAsBase64}`);
This assumes that your image is stored in PNG format, which is quite popular. If you use some other image format (e.g. JPEG), modify the MIME type ("image/..."
part) in the URL accordingly.
Similar Questions:
The following is not exactly the same but similar, I was searching for a snippet to add a call to the interface method, but found this question, so I decided to add this snippet for those who were searching for it like me and found this question:
public class MyClass
{
//... class code goes here
public interface DataLoadFinishedListener {
public void onDataLoadFinishedListener(int data_type);
}
private DataLoadFinishedListener m_lDataLoadFinished;
public void setDataLoadFinishedListener(DataLoadFinishedListener dlf){
this.m_lDataLoadFinished = dlf;
}
private void someOtherMethodOfMyClass()
{
m_lDataLoadFinished.onDataLoadFinishedListener(1);
}
}
Usage is as follows:
myClassObj.setDataLoadFinishedListener(new MyClass.DataLoadFinishedListener() {
@Override
public void onDataLoadFinishedListener(int data_type) {
}
});
This module is added automatically when you run ionic command. However it's not necessery. So an alternative solution is to remove add-event.module.ts from the project.
keytool -import -v -alias cacerts -keystore cacerts.jks -storepass changeit -file C:\cacerts.cer
Thanks for all help at this issue. I'll post here my solution:
Package Header
CREATE OR REPLACE PACKAGE X IS
TYPE exch_row IS RECORD(
currency_cd VARCHAR2(9),
exch_rt_eur NUMBER,
exch_rt_usd NUMBER);
TYPE exch_tbl IS TABLE OF X.exch_row;
FUNCTION GetExchangeRate RETURN X.exch_tbl PIPELINED;
END X;
Package Body
CREATE OR REPLACE PACKAGE BODY X IS
FUNCTION GetExchangeRate RETURN X.exch_tbl
PIPELINED AS
exch_rt_usd NUMBER := 1.0; --todo
rw exch_row;
BEGIN
FOR rw IN (SELECT c.currency_cd AS currency_cd, e.exch_rt AS exch_rt_eur, (e.exch_rt / exch_rt_usd) AS exch_rt_usd
FROM exch e, currency c
WHERE c.currency_key = e.currency_key
) LOOP
PIPE ROW(rw);
END LOOP;
END;
PROCEDURE DoIt IS
BEGIN
DECLARE
CURSOR c0 IS
SELECT i.DOC,
i.doc_currency,
i.net_value,
i.net_value / rt.exch_rt_usd AS net_value_in_usd,
i.net_value / rt.exch_rt_eur AS net_value_in_euro,
FROM item i, (SELECT * FROM TABLE(X.GetExchangeRate())) rt
WHERE i.doc_currency = rt.currency_cd;
TYPE c0_type IS TABLE OF c0%ROWTYPE;
items c0_type;
BEGIN
OPEN c0;
LOOP
FETCH c0 BULK COLLECT
INTO items LIMIT batchsize;
EXIT WHEN items.COUNT = 0;
FORALL i IN items.FIRST .. items.LAST SAVE EXCEPTIONS
INSERT INTO detail_items VALUES items (i);
END LOOP;
CLOSE c0;
COMMIT;
EXCEPTION
WHEN OTHERS THEN
RAISE;
END;
END;
END X;
Please review.
$(window).height();
To set anything in the middle you can use CSS.
<style>
#divCentre
{
position: absolute;
left: 50%;
top: 50%;
width: 300px;
height: 400px;
margin-left: -150px;
margin-top: -200px;
}
</style>
<div id="divCentre">I am at the centre</div>
this
is the DOM element on which the event was hooked. this.id
is its ID. No need to wrap it in a jQuery instance to get it, the id
property reflects the attribute reliably on all browsers.
$("select").change(function() {
alert("Changed: " + this.id);
}
You're not doing this in your code sample, but if you were watching a container with several form elements, that would give you the ID of the container. If you want the ID of the element that triggered the event, you could get that from the event
object's target
property:
$("#container").change(function(event) {
alert("Field " + event.target.id + " changed");
});
(jQuery ensures that the change
event bubbles, even on IE where it doesn't natively.)
Can also use the following code to check the nginx status:
sudo /etc/init.d/nginx status
you can use pow(base, exponent)
from #include <math.h>
or create your own:
int myPow(int x,int n)
{
int i; /* Variable used in loop counter */
int number = 1;
for (i = 0; i < n; ++i)
number *= x;
return(number);
}
Here is a fast native head command that gives you the first 9 lines in DOS.
findstr /n "." myfile.txt | findstr "^.:"
The first 2 characters on each line will be the line number.
I also came across this problem. Google detected my Mac as a new device and blocked it. To unblock, in a web browser log in to your Google account and go to "Account Settings".
Scroll down and you'll find "Recent activities". Click just below that on "Devices".
Your device will be listed. Okay your device. SMTP started working for me after I did this and lowered the protection as mentioned above.
Sounds like you've either hidden JavaScript logs or specified that you only want to see Errors or Warnings. Open Chrome's Developer Tools and go to the Console tab. At the bottom you want to ensure that JavaScript is ticked and also ensure that you have "All", "Logs" or "Debug" selected.
In the image above I have JavaScript, Network, Logging, CSS and Other ticked and "All" selected.
Another potential problem could be that your $(window).scroll()
function isn't wrapped within a .ready()
function (as documented here):
$(document).ready(function() {
$(window).scroll(function() {
...
});
});
When pasting your code into JSFiddle and giving some dummy content, your code works perfectly fine: JSFiddle demo.
The question was edited. The new code given throws two errors:
Uncaught ReferenceError: fitHeight is not defined Uncaught TypeError: Cannot read property 'addEventListener' of null
Because of this, the code stops execution prior to reaching any console.log
call.
I had this same problem, and @AniaG's solution in the comments worked for me.
src
folderAdding this in the index.html
head worked for me:
<style>
html, body, #app, #app>div { position: absolute; width: 100% !important; height: 100% !important; }
</style>
Use this to create your images and put them in specific resource folder.
Maybe remove the semi-colon after set because now the where statement doesn't belong to the update statement. Also the idRequest
could be a problem, better write BookingRequest.idRequest
SELECT ( Schema_name(A.schema_id) + '.' + A.NAME ) AS TableName,
Sum(B.rows)AS RecordCount
FROM sys.objects A INNER JOIN sys.partitions B
ON A.object_id = B.object_id WHERE A.type = 'U'
GROUP BY A.schema_id,A.NAME ;
[Custom ListView with CheckBox]
If customlayout use checkbox, you must set checkbox focusable = false
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:id="@+id/rowTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:textSize="16sp" >
</TextView>
<CheckBox android:id="@+id/CheckBox01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:layout_alignParentRight="true"
android:layout_marginRight="6sp"
android:focusable="false"> // <---important
</CheckBox>
</RelativeLayout>
Readmore : A ListView with Checkboxes (Without Using ListActivity)
try
s.replace(/^0/,'')
console.log("0string =>", "0string".replace(/^0/,'') );_x000D_
console.log("00string =>", "00string".replace(/^0/,'') );_x000D_
console.log("string00 =>", "string00".replace(/^0/,'') );
_x000D_
Now I see what you are doing. You cannot send output to the screen then change the headers. If you are trying to create an XML file of map marker and download them to display, they should be in separate files.
Take this
<?php
require("database.php");
function parseToXML($htmlStr)
{
$xmlStr=str_replace('<','<',$htmlStr);
$xmlStr=str_replace('>','>',$xmlStr);
$xmlStr=str_replace('"','"',$xmlStr);
$xmlStr=str_replace("'",''',$xmlStr);
$xmlStr=str_replace("&",'&',$xmlStr);
return $xmlStr;
}
// Opens a connection to a MySQL server
$connection=mysql_connect (localhost, $username, $password);
if (!$connection) {
die('Not connected : ' . mysql_error());
}
// Set the active MySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
die ('Can\'t use db : ' . mysql_error());
}
// Select all the rows in the markers table
$query = "SELECT * FROM markers WHERE 1";
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
header("Content-type: text/xml");
// Start XML file, echo parent node
echo '<markers>';
// Iterate through the rows, printing XML nodes for each
while ($row = @mysql_fetch_assoc($result)){
// ADD TO XML DOCUMENT NODE
echo '<marker ';
echo 'name="' . parseToXML($row['name']) . '" ';
echo 'address="' . parseToXML($row['address']) . '" ';
echo 'lat="' . $row['lat'] . '" ';
echo 'lng="' . $row['lng'] . '" ';
echo 'type="' . $row['type'] . '" ';
echo '/>';
}
// End XML file
echo '</markers>';
?>
and place it in phpsqlajax_genxml.php
so your javascript can download the XML file. You are trying to do too many things in the same file.
Hope this helps...
class SomeClass{
//Code snippet here...
}
Code snippet 1: Absolutely OK - all checked exceptions handled
static void m1(){
try{
throw new Exception();
} catch(Exception e){
System.out.println(e);
}
}
static{
m1();
}
Code snippet 2: Won't compile - unreported checked exception
static void m1() throws Exception{
throw new Exception();
}
static{
m1();
}
Code snippet 3: OK (see code snippet 1)
static void m1() throws Exception{
throw new Exception();
}
static{
try{m1();}
catch(Exception e){
System.out.println(e);
//or whatever
}
}
Code snippet 4: Compilation error, initilalizer must be able to complete normally
static{
throw new RuntimeException();
}
Basically it boils down to this:
This makes sense as A CLASS SHOULD BE ABLE TO COMPLETE INITIALIZATION NORMALLY. If this happens to be a problem, this should be categorized as an Error (from which recovery is usually difficult or impossible) rather than an Exception (which is usually recoverable)...
BEGIN
FOR r IN (select sid,serial# from v$session where username='user')
LOOP
EXECUTE IMMEDIATE 'alter system kill session ''' || r.sid || ',' || r.serial# || '''';
END LOOP;
END;
/
It works for me.
Just came across this myself.
Finally found my issue was with a .png file that I added that had a capital letter in it an caused exactly the same problem. Eclipse never flagged the file until I closed it and opened Eclipse back up.
$("#my-select option:contains(" + myText +")").attr("selected", true);
This returns the first option containing your text description.
As simple as this:
li = [0, 1, 2, 3]
while 1:
for i, item in enumerate(x):
k = i + 1 if i != len(x) - 1 else 0
print('Current index {} : {}'.format(i,li[k]))
Yes, fork is a clone. It emerged because, you cannot push to others' copies without their permission. They make a copy of it for you (fork), where you will have write permission as well.
In the future if the actual owner or others users with a fork like your changes they can pull it back to their own repository. Alternatively you can send them a "pull-request".
I would try this first
select * from employee where month(current_date)-3 = month(joining_date)
This does the trick, without the need to add an inline style
<div class="row-fluid">
<div class="span6">
<p>text left</p>
</div>
<div class="span6">
<div class="pull-right">
<p>text right</p>
</div>
</div>
</div>
The answer is in nesting another <div>
with the "pull-right" class. Combining the two classes won't work.
Modern browsers do not currently implement JSONRequest (as far as I know) since it is only a draft right now. I have found someone who has implemented it as a library that you can include in your page: http://devpro.it/JSON/files/JSONRequest-js.html (please note that it has a few dependencies).
Otherwise, you might want to go with another JS library like jQuery or Mootools.
Use Spring's "PropertyPlaceholderConfigurer" class
A simple example showing property file read dynamically as bean's property
<bean id="placeholderConfig"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>/WEB-INF/classes/config_properties/dev/database.properties</value>
</list>
</property>
</bean>
<bean id="devDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="driverClass" value="${dev.app.jdbc.driver}"/>
<property name="jdbcUrl" value="${dev.app.jdbc.url}"/>
<property name="user" value="${dev.app.jdbc.username}"/>
<property name="password" value="${dev.app.jdbc.password}"/>
<property name="acquireIncrement" value="3"/>
<property name="minPoolSize" value="5"/>
<property name="maxPoolSize" value="10"/>
<property name="maxStatementsPerConnection" value="11000"/>
<property name="numHelperThreads" value="8"/>
<property name="idleConnectionTestPeriod" value="300"/>
<property name="preferredTestQuery" value="SELECT 0"/>
</bean>
Property File
dev.app.jdbc.driver=com.mysql.jdbc.Driver
dev.app.jdbc.url=jdbc:mysql://localhost:3306/addvertisement
dev.app.jdbc.username=root
dev.app.jdbc.password=root
The data binding implementation must be in the onCreateView
method of the fragment, delete any data Binding that exist in your OnCreate
method,
your onCreateView
should look like this:
public View onCreateView(LayoutInflater inflater,
@Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
MartianDataBinding binding = DataBindingUtil.inflate(
inflater, R.layout.martian_data, container, false);
View view = binding.getRoot();
//here data must be an instance of the class MarsDataProvider
binding.setMarsdata(data);
return view;
}
JavaScript has associative arrays.
Here is a working snippet.
<script type="text/javascript">
var myArray = [];
myArray['thank'] = 'you';
myArray['no'] = 'problem';
console.log(myArray);
</script>
_x000D_
They are simply called objects.
In the Facebook SDK Graph API v2.0 or above, you must request the user_friends permission from each user in the time of Facebook login since user_friends is no longer included by default in every login; we have to add that.
Each user must grant the user_friends permission in order to appear in the response to /me/friends.
let fbLoginManager : FBSDKLoginManager = FBSDKLoginManager()
fbLoginManager.loginBehavior = FBSDKLoginBehavior.web
fbLoginManager.logIn(withReadPermissions: ["email","user_friends","public_profile"], from: self) { (result, error) in
if (error == nil) {
let fbloginresult : FBSDKLoginManagerLoginResult = result!
if fbloginresult.grantedPermissions != nil {
if (fbloginresult.grantedPermissions.contains("email")) {
// Do the stuff
}
else {
}
}
else {
}
}
}
So at the time of Facebook login, it prompts with a screen which contain all the permissions:
If the user presses the Continue button, the permissions will be set. When you access the friends list using Graph API, your friends who logged into the application as above will be listed
if ((FBSDKAccessToken.current()) != nil) {
FBSDKGraphRequest(graphPath: "/me/friends", parameters: ["fields" : "id,name"]).start(completionHandler: { (connection, result, error) -> Void in
if (error == nil) {
print(result!)
}
})
}
The output will contain the users who granted the user_friends permission at the time of login to your application through Facebook.
{
data = (
{
id = xxxxxxxxxx;
name = "xxxxxxxx";
}
);
paging = {
cursors = {
after = xxxxxx;
before = xxxxxxx;
};
};
summary = {
"total_count" = 8;
};
}
Newer versions of Groovy (1.7.2+) offer a JDK extension to more easily traverse over files in a directory, for example:
import static groovy.io.FileType.FILES
def dir = new File(".");
def files = [];
dir.traverse(type: FILES, maxDepth: 0) { files.add(it) };
See also [1] for more examples.
[1] http://mrhaki.blogspot.nl/2010/04/groovy-goodness-traversing-directory.html
I've came through a case recently where I've needed check value of checkbox when user clicked on button. The only proper way to do so is to use prop()
attribute.
var ansValue = $("#ans").prop('checked') ? $("#ans").val() : 0;
this worked in my case maybe someone will need it.
When I've tried .attr(':checked')
it returned checked
but I wanted boolean value and .val()
returned value of attribute value
.
Since November 2017, one can use tomcat8-maven-plugin:
<!-- https://mvnrepository.com/artifact/org.apache.tomcat.maven/tomcat8-maven-plugin -->
<dependency>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat8-maven-plugin</artifactId>
<version>2.2</version>
</dependency>
Note that this plugin resides in ICM repo (not in Maven Central), hence you should add the repo to your pluginsRepositories in your pom.xml:
<pluginRepositories>
<pluginRepository>
<id>icm</id>
<name>Spring Framework Milestone Repository</name>
<url>http://maven.icm.edu.pl/artifactory/repo</url>
</pluginRepository>
</pluginRepositories>
The default sort for arrays in Javascript is an alphabetical search. If you want a numerical sort, try something like this:
var a = [ 1, 100, 50, 2, 5];
a.sort(function(a,b) { return a - b; });
BigInteger has a constructor where you can pass string as an argument.
try below,
private void sum(String newNumber) {
// BigInteger is immutable, reassign the variable:
this.sum = this.sum.add(new BigInteger(newNumber));
}
X
is a dataframe and can't be accessed via slice terminology like X[:, 3]
. You must access via iloc
or X.values
. However, the way you constructed X
made it a copy... so. I'd use values
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
# dataset = pd.read_csv('50_Startups.csv')
dataset = pd.DataFrame(np.random.rand(10, 10))
y=dataset.iloc[:, 4]
X=dataset.iloc[:, 0:4]
# Encoding categorical data
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
labelencoder_X = LabelEncoder()
# I changed this line
X.values[:, 3] = labelencoder_X.fit_transform(X.values[:, 3])
ser.read(64)
should be ser.read(size=64)
; ser.read uses keyword arguments, not positional.
Also, you're reading from the port twice; what you probably want to do is this:
i=0
for modem in PortList:
for port in modem:
try:
ser = serial.Serial(port, 9600, timeout=1)
ser.close()
ser.open()
ser.write("ati")
time.sleep(3)
read_val = ser.read(size=64)
print read_val
if read_val is not '':
print port
except serial.SerialException:
continue
i+=1
The normal way to control this is with git config
For example
git config --global core.autocrlf true
For details, scroll down in this link to Pro Git to the section named "core.autocrlf"
If you want to know what file this is saved in, you can run the command:
git config --global --edit
and the git global config file should open in a text editor, and you can see where that file was loaded from.
I find this lecture very valuable https://vimeo.com/190275665, in point 3 it summarizes these generators and also gives some performance analysis and guideline one when you use each one.
Get the number of options in a particular select element
$("#elementid option").length
//Convert input format 19-FEB-16 01.00.00.000000000 PM to 2016-02-19 01.00.000 PM
SimpleDateFormat inFormat = new SimpleDateFormat("dd-MMM-yy hh.mm.ss.SSSSSSSSS aaa");
Date today = new Date();
Date d1 = inFormat.parse("19-FEB-16 01.00.00.000000000 PM");
SimpleDateFormat outFormat = new SimpleDateFormat("yyyy-MM-dd hh.mm.ss.SSS aaa");
System.out.println("Out date ="+outFormat.format(d1));
The following is equivalent to your second code block:
var f = function () {
//Some logic here...
};
var fr = f;
fr(pars);
If you want to actually pass a reference to a function to some other function, you can do something like this:
function fiz(x, y, z) {
return x + y + z;
}
// elsewhere...
function foo(fn, p, q, r) {
return function () {
return fn(p, q, r);
}
}
// finally...
f = foo(fiz, 1, 2, 3);
f(); // returns 6
You're almost certainly better off using a framework for this sort of thing, though.
I think what you're looking for is:
textBox1.Select();
in the constructor. (This is in C#. Maybe in VB that would be the same but without the semicolon.)
From http://msdn.microsoft.com/en-us/library/system.windows.forms.control.focus.aspx :
Focus is a low-level method intended primarily for custom control authors. Instead, application programmers should use the Select method or the ActiveControl property for child controls, or the Activate method for forms.
For me it turned out that the service wasn't running at all. Check with
service cassandra status
If you got the same error as I got, or another type, then messing around with IP addresses won't solve your problem at all.
The error I got:
cassandra dead but pid file exists
Edit: This was the solution for my problem: https://stackoverflow.com/a/46743119/3881406
UTF-8 is prepared for world domination, Latin1 isn't.
If you're trying to store non-Latin characters like Chinese, Japanese, Hebrew, Russian, etc using Latin1 encoding, then they will end up as mojibake. You may find the introductory text of this article useful (and even more if you know a bit Java).
Note that full 4-byte UTF-8 support was only introduced in MySQL 5.5. Before that version, it only goes up to 3 bytes per character, not 4 bytes per character. So, it supported only the BMP plane and not e.g. the Emoji plane. If you want full 4-byte UTF-8 support, upgrade MySQL to at least 5.5 or go for another RDBMS like PostgreSQL. In MySQL 5.5+ it's called utf8mb4
.
add your script tag on the bottom of the body tag. so that script loads after html content then you won't get such error and add=
This can also happen when you're trying to load a DLL and that in turn needs another DLL which cannot be not found.
In Android 4
Go to Setting->Location services->
Uncheck Google`s location service.
Check GPS satelites.
For test you can use GPS Test.Please test Outdoor!
Offline maps are available on new version of Google map.
e.g.,
os.rename(file_name, file_name.translate({ord(c): None for c in '0123456789'}))
To remove all the number from the string
There's a BeyondCompare plugin as well. It opens the 2 files in a BeyondCompare
window. Pretty convenient to open files from the sublime window.
You will need BC3 installation present in the system. After installing the plugin, you will have to provide the path to the installation.
Example:
{
//Define a custom path to beyond compare
"beyond_compare_path": "G:/Softwares/Beyond Compare 3/BCompare.exe"
}
Simple!!
one line:
var res = test.Select(x => new string(x, 1)).ToArray();
System.Interactive provides Buffer()
for this purpose. Some quick testing shows performance is similar to Sam's solution.
When you use a TemplateField and bind literal text to it like you are doing, asp.net will actually insert a control FOR YOU! It gets put into a DataBoundLiteralControl. You can see this if you look in the debugger near your line of code that is getting the empty text.
So, to access the information without changing your template to use a control, you would cast like this:
string percentage = ((DataBoundLiteralControl)e.Row.Cells[7].Controls[0]).Text;
That will get you your text!
With Spring boot , the spring.config.location does work,just provide comma separated properties files.
see the below code
@PropertySource(ignoreResourceNotFound=true,value="classpath:jdbc-${spring.profiles.active}.properties")
public class DBConfig{
@Value("${jdbc.host}")
private String jdbcHostName;
}
}
one can put the default version of jdbc.properties inside application. The external versions can be set lie this.
java -jar target/myapp.jar --spring.config.location=classpath:file:///C:/Apps/springtest/jdbc.properties,classpath:file:///C:/Apps/springtest/jdbc-dev.properties
Based on profile value set using spring.profiles.active property, the value of jdbc.host will be picked up. So when (on windows)
set spring.profiles.active=dev
jdbc.host will take value from jdbc-dev.properties.
for
set spring.profiles.active=default
jdbc.host will take value from jdbc.properties.
Posting an answer at the behest of commenters on my answer to a similar question where the same technique was used to mutate the last line of a file, not just get it.
For a file of significant size, mmap
is the best way to do this. To improve on the existing mmap
answer, this version is portable between Windows and Linux, and should run faster (though it won't work without some modifications on 32 bit Python with files in the GB range, see the other answer for hints on handling this, and for modifying to work on Python 2).
import io # Gets consistent version of open for both Py2.7 and Py3.x
import itertools
import mmap
def skip_back_lines(mm, numlines, startidx):
'''Factored out to simplify handling of n and offset'''
for _ in itertools.repeat(None, numlines):
startidx = mm.rfind(b'\n', 0, startidx)
if startidx < 0:
break
return startidx
def tail(f, n, offset=0):
# Reopen file in binary mode
with io.open(f.name, 'rb') as binf, mmap.mmap(binf.fileno(), 0, access=mmap.ACCESS_READ) as mm:
# len(mm) - 1 handles files ending w/newline by getting the prior line
startofline = skip_back_lines(mm, offset, len(mm) - 1)
if startofline < 0:
return [] # Offset lines consumed whole file, nothing to return
# If using a generator function (yield-ing, see below),
# this should be a plain return, no empty list
endoflines = startofline + 1 # Slice end to omit offset lines
# Find start of lines to capture (add 1 to move from newline to beginning of following line)
startofline = skip_back_lines(mm, n, startofline) + 1
# Passing True to splitlines makes it return the list of lines without
# removing the trailing newline (if any), so list mimics f.readlines()
return mm[startofline:endoflines].splitlines(True)
# If Windows style \r\n newlines need to be normalized to \n, and input
# is ASCII compatible, can normalize newlines with:
# return mm[startofline:endoflines].replace(os.linesep.encode('ascii'), b'\n').splitlines(True)
This assumes the number of lines tailed is small enough you can safely read them all into memory at once; you could also make this a generator function and manually read a line at a time by replacing the final line with:
mm.seek(startofline)
# Call mm.readline n times, or until EOF, whichever comes first
# Python 3.2 and earlier:
for line in itertools.islice(iter(mm.readline, b''), n):
yield line
# 3.3+:
yield from itertools.islice(iter(mm.readline, b''), n)
Lastly, this read in binary mode (necessary to use mmap
) so it gives str
lines (Py2) and bytes
lines (Py3); if you want unicode
(Py2) or str
(Py3), the iterative approach could be tweaked to decode for you and/or fix newlines:
lines = itertools.islice(iter(mm.readline, b''), n)
if f.encoding: # Decode if the passed file was opened with a specific encoding
lines = (line.decode(f.encoding) for line in lines)
if 'b' not in f.mode: # Fix line breaks if passed file opened in text mode
lines = (line.replace(os.linesep, '\n') for line in lines)
# Python 3.2 and earlier:
for line in lines:
yield line
# 3.3+:
yield from lines
Note: I typed this all up on a machine where I lack access to Python to test. Please let me know if I typoed anything; this was similar enough to my other answer that I think it should work, but the tweaks (e.g. handling an offset
) could lead to subtle errors. Please let me know in the comments if there are any mistakes.
I prefer to use BINARY(32) since it's the optimized way!
You can place in that 32 hex digits from (00 to FF).
Therefore BINARY(32)!
jQuery(document).ready(function(){
jQuery("#id").change(function() {
var value = jQuery(this).children(":selected").attr("value");
alert(value);
});
})
–npm install --save or -S: When the following command is used with npm install this will save all your installed core packages into the dependency section in the package.json file. Core dependencies are those packages without which your application will not give the desired results. But as mentioned earlier, it is an unnecessary feature in the npm 5.0.0 version onwards.
npm install --save
Or without the year:
DateTime.Now.ToString("M/dd")
My solution in code behind was:
System.Web.UI.WebControls.FileUpload fileUpload;
I don't know why, but when you are using FileUpload without System.Web.UI.WebControls it is referencing to YourProject.FileUpload not System.Web.UI.WebControls.FileUpload.
You can now simply do Instant.parse("2015-04-28T14:23:38.521Z")
and get the correct thing now, especially since you should be using Instant
instead of the broken java.util.Date
with the most recent versions of Java.
You should be using DateTimeFormatter
instead of SimpleDateFormatter
as well.
The explanation below is still valid as as what the format represents. But it was written before Java 8 was ubiquitous so it uses the old classes that you should not be using if you are using Java 8 or higher.
Z
as demonstrated:In the pattern the
T
is escaped with'
on either side.The pattern for the
Z
at the end is actuallyXXX
as documented in the JavaDoc forSimpleDateFormat
, it is just not very clear on actually how to use it sinceZ
is the marker for the oldTimeZone
information as well.
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;
public class Q2597083
{
/**
* All Dates are normalized to UTC, it is up the client code to convert to the appropriate TimeZone.
*/
public static final TimeZone UTC;
/**
* @see <a href="http://en.wikipedia.org/wiki/ISO_8601#Combined_date_and_time_representations">Combined Date and Time Representations</a>
*/
public static final String ISO_8601_24H_FULL_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX";
/**
* 0001-01-01T00:00:00.000Z
*/
public static final Date BEGINNING_OF_TIME;
/**
* 292278994-08-17T07:12:55.807Z
*/
public static final Date END_OF_TIME;
static
{
UTC = TimeZone.getTimeZone("UTC");
TimeZone.setDefault(UTC);
final Calendar c = new GregorianCalendar(UTC);
c.set(1, 0, 1, 0, 0, 0);
c.set(Calendar.MILLISECOND, 0);
BEGINNING_OF_TIME = c.getTime();
c.setTime(new Date(Long.MAX_VALUE));
END_OF_TIME = c.getTime();
}
public static void main(String[] args) throws Exception
{
final SimpleDateFormat sdf = new SimpleDateFormat(ISO_8601_24H_FULL_FORMAT);
sdf.setTimeZone(UTC);
System.out.println("sdf.format(BEGINNING_OF_TIME) = " + sdf.format(BEGINNING_OF_TIME));
System.out.println("sdf.format(END_OF_TIME) = " + sdf.format(END_OF_TIME));
System.out.println("sdf.format(new Date()) = " + sdf.format(new Date()));
System.out.println("sdf.parse(\"2015-04-28T14:23:38.521Z\") = " + sdf.parse("2015-04-28T14:23:38.521Z"));
System.out.println("sdf.parse(\"0001-01-01T00:00:00.000Z\") = " + sdf.parse("0001-01-01T00:00:00.000Z"));
System.out.println("sdf.parse(\"292278994-08-17T07:12:55.807Z\") = " + sdf.parse("292278994-08-17T07:12:55.807Z"));
}
}
sdf.format(BEGINNING_OF_TIME) = 0001-01-01T00:00:00.000Z
sdf.format(END_OF_TIME) = 292278994-08-17T07:12:55.807Z
sdf.format(new Date()) = 2015-04-28T14:38:25.956Z
sdf.parse("2015-04-28T14:23:38.521Z") = Tue Apr 28 14:23:38 UTC 2015
sdf.parse("0001-01-01T00:00:00.000Z") = Sat Jan 01 00:00:00 UTC 1
sdf.parse("292278994-08-17T07:12:55.807Z") = Sun Aug 17 07:12:55 UTC 292278994
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;
Assuming you want curl installed: just execute the install command and see what happens.
$ sudo yum install curl
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
* base: mirrors.cat.pdx.edu
* epel: mirrors.kernel.org
* extras: mirrors.cat.pdx.edu
* remi-php72: repo1.sea.innoscale.net
* remi-safe: repo1.sea.innoscale.net
* updates: mirrors.cat.pdx.edu
Package curl-7.29.0-54.el7_7.1.x86_64 already installed and latest version
Nothing to do
Hope this will help you. Assumed that login form has: username and password inputs.
if(isset($_POST['username']) && trim($_POST['username']) != "" && isset($_POST['password']) && trim($_POST['password']) != ""){
//login
} else {
//register
}
While JonSkeet's answer explains the difference in a typically excellent way there is another difference: exception handling.
Task.WaitAll
throws an AggregateException
when any of the tasks throws and you can examine all thrown exceptions. The await
in await Task.WhenAll
unwraps the AggregateException
and 'returns' only the first exception.
When the program below executes with await Task.WhenAll(taskArray)
the output is as follows.
19/11/2016 12:18:37 AM: Task 1 started
19/11/2016 12:18:37 AM: Task 3 started
19/11/2016 12:18:37 AM: Task 2 started
Caught Exception in Main at 19/11/2016 12:18:40 AM: Task 1 throwing at 19/11/2016 12:18:38 AM
Done.
When the program below is executed with Task.WaitAll(taskArray)
the output is as follows.
19/11/2016 12:19:29 AM: Task 1 started
19/11/2016 12:19:29 AM: Task 2 started
19/11/2016 12:19:29 AM: Task 3 started
Caught AggregateException in Main at 19/11/2016 12:19:32 AM: Task 1 throwing at 19/11/2016 12:19:30 AM
Caught AggregateException in Main at 19/11/2016 12:19:32 AM: Task 2 throwing at 19/11/2016 12:19:31 AM
Caught AggregateException in Main at 19/11/2016 12:19:32 AM: Task 3 throwing at 19/11/2016 12:19:32 AM
Done.
The program:
class MyAmazingProgram
{
public class CustomException : Exception
{
public CustomException(String message) : base(message)
{ }
}
static void WaitAndThrow(int id, int waitInMs)
{
Console.WriteLine($"{DateTime.UtcNow}: Task {id} started");
Thread.Sleep(waitInMs);
throw new CustomException($"Task {id} throwing at {DateTime.UtcNow}");
}
static void Main(string[] args)
{
Task.Run(async () =>
{
await MyAmazingMethodAsync();
}).Wait();
}
static async Task MyAmazingMethodAsync()
{
try
{
Task[] taskArray = { Task.Factory.StartNew(() => WaitAndThrow(1, 1000)),
Task.Factory.StartNew(() => WaitAndThrow(2, 2000)),
Task.Factory.StartNew(() => WaitAndThrow(3, 3000)) };
Task.WaitAll(taskArray);
//await Task.WhenAll(taskArray);
Console.WriteLine("This isn't going to happen");
}
catch (AggregateException ex)
{
foreach (var inner in ex.InnerExceptions)
{
Console.WriteLine($"Caught AggregateException in Main at {DateTime.UtcNow}: " + inner.Message);
}
}
catch (Exception ex)
{
Console.WriteLine($"Caught Exception in Main at {DateTime.UtcNow}: " + ex.Message);
}
Console.WriteLine("Done.");
Console.ReadLine();
}
}
A similar option in Sublime Text is the built in Edit->Line->Reindent
. You can put this code in Preferences -> Key Bindings User
:
{ "keys": ["alt+shift+f"], "command": "reindent"}
I use alt+shift+f because I'm a Netbeans user.
To format your code, select all by pressing ctrl+a and "your key combination". Excuse me for my bad english.
Or if you don't want to select all before formatting, add an argument to the command instead:
{ "keys": ["alt+shift+f"], "command": "reindent", "args": {"single_line": false} }
(as per comment by @Supr below)
Same here on Ubuntu 18.04
Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock'
/run/mysqld/
?> / ll /var/run
lrwxrwxrwx 1 root root 4 Nov 1 2018 /var/run -> /run/
hmmm... Does that mean a symbolic link won't work? That's weird...
I have installed Node.js on an iMac and
node somefile.js
in bash will work.
Bootstrap 4.0
Be aware of all migration changes from Bootstrap 3 to 4. On the table you now need to enable flex box by adding the class d-flex
, and drop the xs
to allow bootstrap to automatically detect the viewport.
<div class="container-fluid">
<table id="productSizes" class="table">
<thead>
<tr class="d-flex">
<th class="col-1">Size</th>
<th class="col-3">Bust</th>
<th class="col-3">Waist</th>
<th class="col-5">Hips</th>
</tr>
</thead>
<tbody>
<tr class="d-flex">
<td class="col-1">6</td>
<td class="col-3">79 - 81</td>
<td class="col-3">61 - 63</td>
<td class="col-5">89 - 91</td>
</tr>
<tr class="d-flex">
<td class="col-1">8</td>
<td class="col-3">84 - 86</td>
<td class="col-3">66 - 68</td>
<td class="col-5">94 - 96</td>
</tr>
</tbody>
</table>
Bootstrap 3.2
Table column width use the same layout as grids do; using col-[viewport]-[size]
. Remember the column sizes should total 12; 1 + 3 + 3 + 5 = 12
in this example.
<thead>
<tr>
<th class="col-xs-1">Size</th>
<th class="col-xs-3">Bust</th>
<th class="col-xs-3">Waist</th>
<th class="col-xs-5">Hips</th>
</tr>
</thead>
Remember to set the <th>
elements rather than the <td>
elements so it sets the whole column. Here is a working BOOTPLY.
Thanks to @Dan for reminding me to always work mobile view (col-xs-*
) first.
You can simply import by
mysqlimport --ignore-lines=1 --lines-terminated-by='\n' --fields-terminated-by=',' --fields-enclosed-by='"' --verbose --local -uroot -proot db_name csv_import.csv
Note: Csv File name and Table name should be same
You can create a static method that will return desired IEnumerable like this :
public static IEnumerable<T> CreateEnumerable<T>(params T[] values) =>
values;
//And then use it
IEnumerable<string> myStrings = CreateEnumerable("first item", "second item");//etc..
Alternatively just do :
IEnumerable<string> myStrings = new []{ "first item", "second item"};
The main reason ++ comes in handy in C-like languages is for keeping track of indices. In Python, you deal with data in an abstract way and seldom increment through indices and such. The closest-in-spirit thing to ++
is the next
method of iterators.
To expand a bit on why the error happened: A forward slash at the beginning of a path means "start from the root of the filesystem, and look for the given path". No forward slash means "start from the current working directory, and look for the given path".
The path
/tmp/test.jpg
thus translates to looking for the file test.jpg in the tmp folder at the root of the filesystem (e.g. c:\ on windows, / on *nix), instead of the webapp folder. Adding a period (.) in front of the path explicitly changes this to read "start from the current working directory", but is basically the same as leaving the forward slash out completely.
./tmp/test.jpg = tmp/test.jpg
Check what your environment variable DISPLAY's value is. Try running a simple X application from the command line. If it works, check DISPLAY's value for the right value.
You can experiment with different values of and environment variable on a per invocation basis by doing the following on the command line:
DISPLAY=:0.0 <your-java-executable-here>
How are you calling your program?
Based on posted answered, this worked for me:
/* check for iOS 6 or 7 */
if ([[self navigationController].navigationBar respondsToSelector:@selector(setBarTintColor:)]) {
[[self navigationController].navigationBar setBarTintColor:[UIColor whiteColor]];
} else {
/* Set background and foreground */
[[self navigationController].navigationBar setTintColor:[UIColor whiteColor]];
[self navigationController].navigationBar.titleTextAttributes = [[NSDictionary alloc] initWithObjectsAndKeys:[UIColor blackColor],UITextAttributeTextColor,nil];
}
If you already have nodejs installed (check with which nodejs
) and don't want to install another package, you can, as root:
update-alternatives --install /usr/bin/node node /usr/bin/nodejs 99
There are two types of WITH clauses:
Here is the FizzBuzz in SQL form, using a WITH common table expression (CTE).
;WITH mil AS (
SELECT TOP 1000000 ROW_NUMBER() OVER ( ORDER BY c.column_id ) [n]
FROM master.sys.all_columns as c
CROSS JOIN master.sys.all_columns as c2
)
SELECT CASE WHEN n % 3 = 0 THEN
CASE WHEN n % 5 = 0 THEN 'FizzBuzz' ELSE 'Fizz' END
WHEN n % 5 = 0 THEN 'Buzz'
ELSE CAST(n AS char(6))
END + CHAR(13)
FROM mil
Here is a select statement also using a WITH clause
SELECT * FROM orders WITH (NOLOCK) where order_id = 123
Is there a prize for being lazy and using the transpose function of NumPy arrays? ;)
import numpy as np
a = np.array([(1,2,3), (4,5,6)])
b = a.transpose()
Telerik's Just Decompile is the best I've used. It's free once you sign up with an email.
You get this error message if a Python file was closed from "the outside", i.e. not from the file object's close()
method:
>>> f = open(".bashrc")
>>> os.close(f.fileno())
>>> del f
close failed in file object destructor:
IOError: [Errno 9] Bad file descriptor
The line del f
deletes the last reference to the file object, causing its destructor file.__del__
to be called. The internal state of the file object indicates the file is still open since f.close()
was never called, so the destructor tries to close the file. The OS subsequently throws an error because of the attempt to close a file that's not open.
Since the implementation of os.system()
does not create any Python file objects, it does not seem likely that the system()
call is the origin of the error. Maybe you could show a bit more code?
Oh, dear. A few little problems...
As pointed out by others, you need to quote to protect against empty/space-containing entries, and use the !delayed_expansion! facility.
Two other matters of which you should be aware:
First, set/p
will assign a user-input value to a variable. That's not news - but the gotcha is that pressing enter
in response will leave the variable UNCHANGED - it will not ASSIGN a zero-length string to the variable (hence deleting the variable from the environment.) The safe method is:
set "var="
set /p var=
That is, of course, if you don't WANT enter
to repeat the existing value.
Another useful form is
set "var=default"
set /p var=
or
set "var=default"
set /p "var=[%var%]"
(which prompts with the default value; !var!
if in a block statement with delayedexpansion)
Second issue is that on some Windows versions (although W7 appears to "fix" this issue) ANY label - including a :: comment
(which is a broken-label) will terminate any 'block' - that is, parenthesised compound statement)
IMPORTANT: after 4 hours , working with laravel 5.7 and php 7.+ and run/use php artison serve on localhost trying to connect to mailgun .
IMPORTANT to Resolve the problem do not work with ip http://127.0.0.1:8000 use localhost or set domain name by host file
ok ,
simple google search turned up this:
If the data is actually an HTML page and has NOT been created by ASP, PHP, or some other scripting language, and you are using Internet Explorer 6, and you have Excel installed on your computer, simply right-click on the page and look through the menu. You should see "Export to Microsoft Excel." If all these conditions are true, click on the menu item and after a few prompts it will be imported to Excel.
if you can't do that, he gives an alternate "drag-and-drop" method:
public class BinaryConvert{
public static void main(String[] args){
System.out.println("Binary Result: "+ doBin(45));
}
static String doBin(int n){
int b = 2;
String r = "";
String c = "";
do{
c += (n % b);
n /= b;
}while(n != 0);
for(int i = (c.length() - 1); i >=0; i--){
r += c.charAt(i);
}
return r;
}
}
A Simple Approach will be to use a normal link and add Bootstrap modal effect to it. Just make use of my Code, hopefully you will get it run.
<div class="container">
<div class="row">
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="addContact" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true"><b style="color:#fb3600; font-weight:700;">X</b></button><!--×-->
<h4 class="modal-title text-center" id="addContact">Add Contact</h4>
</div>
<div class="modal-body">
<div class="row">
<ul class="nav nav-tabs">
<li class="active">
<a data-toggle="tab" style="background-color:#f5dfbe" href="#contactTab">Contact</a>
</li>
<li>
<a data-toggle="tab" style="background-color:#a6d2f6" href="#speechTab">Speech</a>
</li>
</ul>
<div class="tab-content">
<div id="contactTab" class="tab-pane in active"><partial name="CreateContactTag"></div>
<div id="speechTab" class="tab-pane fade in"><partial name="CreateSpeechTag"></div>
</div>
</div>
</div>
<div class="modal-footer">
<a class="btn btn-info" data-dismiss="modal">Close</a>
</div>
</div>
</div>
</div>
</div>
</div>
You can simply create a php input form for Varchar date
,give it a varchar
length of lets say 300. Then ask the users to copy and paste the Embed code.When you view the records, you will view the streamed video.
Perhaps not the best options but just another way is to read the Windows Registry in the host machine, on elevated PowerShell prompt you can do something like this:
#Get SQL instance's Port number using Windows Registry:
$instName = (Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Microsoft SQL Server').InstalledInstances[0]
$tcpPort = (Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Microsoft SQL Server\$instName\MSSQLServer\SuperSocketNetLib\Tcp").TcpPort
Write-Host The SQL Instance: `"$instName`" is listening on `"$tcpPort`" "TcpPort."
Ensure to run this PowerShell script in the Host Server (that hosts your SQL instance / SQL Server installation), which means you have to first RDP into the SQL Server/Box/VM, then run this code.
HTH
I resolved this issue by removing a URL reservation that matched my app directory in IIS. I had a similar (definitely not the same) issue as outlined in this article:
In python 3, to get text output:
import io
import urllib.request
response = urllib.request.urlopen("http://google.com")
text = io.TextIOWrapper(response)
For me rollbackFor was not enough, so I had to put this and it works as expected:
@Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackFor = Exception.class)
I hope it helps :-)
preventDefault
is a widespread standard; using an adhoc every time you want to be compliant with old IE versions is cumbersome, better to use a polyfill:
if (typeof Event.prototype.preventDefault === 'undefined') {
Event.prototype.preventDefault = function (e, callback) {
this.returnValue = false;
};
}
This will modify the prototype of the Event and add this function, a great feature of javascript/DOM in general. Now you can use e.preventDefault
with no problem.
Custom made :) you can use dropdown hori/vertical offset properties to position the list currently, also try android:spinnerMode="dialog" it is cooler.
Layout
<LinearLayout
android:layout_marginBottom="20dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<AutoCompleteTextView
android:layout_weight="1"
android:id="@+id/edit_ip"
android:text="default value"
android:layout_width="0dp"
android:layout_height= "wrap_content"/>
<Spinner
android:layout_marginRight="20dp"
android:layout_width="30dp"
android:layout_height="50dp"
android:id="@+id/spinner_ip"
android:spinnerMode="dropdown"
android:entries="@array/myarray"/>
</LinearLayout>
Java
//set auto complete
final AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.edit_ip);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, getResources().getStringArray(R.array.myarray));
textView.setAdapter(adapter);
//set spinner
final Spinner spinner = (Spinner) findViewById(R.id.spinner_ip);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
textView.setText(spinner.getSelectedItem().toString());
textView.dismissDropDown();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
textView.setText(spinner.getSelectedItem().toString());
textView.dismissDropDown();
}
});
res/values/string
<string-array name="myarray">
<item>value1</item>
<item>value2</item>
</string-array>
Was that useful??
IEnumerable list = DataGridDetail.ItemsSource as IEnumerable;
List<string> lstFile = new List<string>();
int i = 0;
foreach (var row in list)
{
bool IsChecked = (bool)((CheckBox)DataGridDetail.Columns[0].GetCellContent(row)).IsChecked;
if (IsChecked)
{
MessageBox.show(i);
--Here i want to get the index or current row from the list
}
++i;
}
One thing you should look into is the SQLite date and time functions, especially if you're going to have to manipulate a lot of dates. It's the sane way to use dates, at the cost of changing the internal format (has to be ISO, i.e. yyyy-MM-dd).
I think error is not coming from the specified line but from the first 3 lines. Try this instead :
node {
stage("first") {
def foo = "foo"
sh "echo ${foo}"
}
}
I think you had some extra lines that are not valid...
From declaractive pipeline model documentation, it seems that you have to use an environment
declaration block to declare your variables, e.g.:
pipeline {
environment {
FOO = "foo"
}
agent none
stages {
stage("first") {
sh "echo ${FOO}"
}
}
}
Look into the XMLSerializer
class.
If you want to save the state of objects and be able to recreate them easily at another time, serialization is your best bet.
Serialize it so you are returned the fully-formed XML. Write this to a file using the StreamWriter
class.
Later, you can read in the contents of your file, and pass it to the serializer class along with an instance of the object you want to populate, and the serializer will take care of deserializing as well.
Here's a code snippet taken from Microsoft Support:
using System;
public class clsPerson
{
public string FirstName;
public string MI;
public string LastName;
}
class class1
{
static void Main(string[] args)
{
clsPerson p=new clsPerson();
p.FirstName = "Jeff";
p.MI = "A";
p.LastName = "Price";
System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(p.GetType());
// at this step, instead of passing Console.Out, you can pass in a
// Streamwriter to write the contents to a file of your choosing.
x.Serialize(Console.Out, p);
Console.WriteLine();
Console.ReadLine();
}
}
gc()
can help
saving data as .RData, closing, re-opening R, and loading the RData can help.
see my answer here: https://stackoverflow.com/a/24754706/190791 for more details
How about i-net Clear Reports (used to be i-net Crystal-Clear).
Though not free, you should also consider this low-cost, non-free, non-open-source reporting solution that can fully compete with Crystal Reports - and is Java-based.
I think it's even more cost efficient than "free ones". A small company may have to think closely about free things, but will then have to invest into manpower to find out how everything works and so on. Large companies will for sure subscribe to premium support services that cost a lot. See this article for reference
i-net Clear Reports has a very low price tag with great support for free and even better premium support via yearly subscriptions.
Disclosure: Yeah, I work for the company who built this, so I'm biased. But I honestly believe in what I just wrote.
Also add cursor:hand. Some browsers need that instead.
I just like to note that I needed this for my Cucumber tests and found out that if you like to simulate pressing the enter/return key, you need to send the :return
value and not the :enter
value (see the values described here)
Try with an address that is not gmail. They do not allow (as far as i know) smpt access to send mail from. I was doing a simple mail program last week and they also dont use default ports to send from and require that you transport across https
There is no way to force EF to improve performance when doing it this way. The problem is that EF executes each insert in separate round trip to the database. Awesome isn't it? Even DataSets supported batch processing. Check this article for some workaround. Another workaround can be using custom stored procedure accepting table valued parameter but you need raw ADO.NET for that.
you can use also..
$('#apply-form input').blur(function()
{
if( $(this).val() == '' ) {
$(this).parents('p').addClass('warning');
}
});
if you have doubt about spaces,then try..
$('#apply-form input').blur(function()
{
if( $(this).val().trim() == '' ) {
$(this).parents('p').addClass('warning');
}
});
DECLARE @vchVAlue NVARCHAR(255) = 'SWP, Lettering Position 1: 4 ?, 2: 8 ?, 3: 16 ?, 4: , 5: , 6: , Voltage Selector, Solder, 6, Step switch, : w/o fuseholder '
WHILE PATINDEX('%?%' , CAST(@vchVAlue AS VARCHAR(255))) > 0
BEGIN
SELECT @vchVAlue = STUFF(@vchVAlue,PATINDEX('%?%' , CAST(@vchVAlue AS VARCHAR(255))),1,' ')
END
SELECT @vchVAlue
I launched ubuntu Xampp server on AWS amazon. And met the same problem with FTP, even though add user to group ftp SFTP and set permissions, owner group of htdocs folder. Finally find the reason in inbound rules in security group, added All TCP, 0 - 65535 rule(0.0.0.0/0,::/0) , then working right!
I would like to propose a generalization with awk.
When the file is made by blocks of a fixed size and the lines to delete are repeated for each block, awk can work fine in such a way
awk '{nl=((NR-1)%2000)+1; if ( (nl<714) || ((nl>1025)&&(nl<1029)) ) print $0}'
OriginFile.dat > MyOutputCuttedFile.dat
In this example the size for the block is 2000 and I want to print the lines [1..713] and [1026..1029].
NR
is the variable used by awk to store the current line number.%
gives the remainder (or modulus) of the division of two integers;nl=((NR-1)%BLOCKSIZE)+1
Here we write in the variable nl the line number inside the current block. (see below)||
and &&
are the logical operator OR and AND.print $0
writes the full lineWhy ((NR-1)%BLOCKSIZE)+1:
(NR-1) We need a shift of one because 1%3=1, 2%3=2, but 3%3=0.
+1 We add again 1 because we want to restore the desired order.
+-----+------+----------+------------+
| NR | NR%3 | (NR-1)%3 | (NR-1)%3+1 |
+-----+------+----------+------------+
| 1 | 1 | 0 | 1 |
| 2 | 2 | 1 | 2 |
| 3 | 0 | 2 | 3 |
| 4 | 1 | 0 | 1 |
+-----+------+----------+------------+
You probably want to use an ExpandableListView, a special ListView that allows you to open and close groups.
What parsers and lexers have in common:
*
, ==
, <=
, ^
will be classified as "operator" token by the C/C++ lexer.[number][operator][number]
, [id][operator][id]
, [id][operator][number][operator][number]
will be classified as "expression" nonterminal by the C/C++ parser.[TXT][TAG][TAG][TXT][TAG][TXT]...
.As you can see, parsers and tokenizers have much in common. One parser can be a tokenizer for other parser, which reads its input tokens as symbols from its own alphabet (tokens are simply symbols of some alphabet) in the same way as sentences from one language can be alphabetic symbols of some other, higher-level language. For example, if *
and -
are the symbols of the alphabet M
(as "Morse code symbols"), then you can build a parser which recognizes strings of these dots and lines as letters encoded in the Morse code. The sentences in the language "Morse Code" could be tokens for some other parser, for which these tokens are atomic symbols of its language (e.g. "English Words" language). And these "English Words" could be tokens (symbols of the alphabet) for some higher-level parser which understands "English Sentences" language. And all these languages differ only in the complexity of the grammar. Nothing more.
So what's all about these "Chomsky's grammar levels"? Well, Noam Chomsky classified grammars into four levels depending on their complexity:
a
,b
), their concatenations (ab
,aba
,bbb
etd.), or alternatives (e.g. a|b
).(()()(()()))
, nested HTML/BBcode tags, nested blocks etc. It's because state automata to deal with it should have to have infinitely many states to handle infinitely many nesting levels.x+3
and in one context this x
could be a name of a variable, and in other context it could be a name of a function etc.Models don't exist in isolation. The structures you'd define for a simulation of cars entering a car park, an embedded system which guides you to a free space, a car parking billing system or for the automated gates/ticket machines usual in car parks are all different.
immutable means you can't not change the value of the same referance.every time you required to create new referance means new memory location. ex:
String str="abc";
str="bcd";
here, in the above code ,in the memory there are 2 blocks for storing the value.the first for value "abc" and second for "bcd".the second value is not replace to first value.
this is call the immutable.
NSMutableDictionary *contentDictionary = [[NSMutableDictionary alloc]init];
[contentDictionary setValue:@"name" forKey:@"email"];
[contentDictionary setValue:@"name" forKey:@"username"];
[contentDictionary setValue:@"name" forKey:@"password"];
[contentDictionary setValue:@"name" forKey:@"firstName"];
[contentDictionary setValue:@"name" forKey:@"lastName"];
NSData *data = [NSJSONSerialization dataWithJSONObject:contentDictionary options:NSJSONWritingPrettyPrinted error:nil];
NSString *jsonStr = [[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding];
NSLog(@"%@",jsonStr);
NSString *urlString = [NSString stringWithFormat:@"http://testgcride.com:8081/v1/users"];
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:[jsonStr dataUsingEncoding:NSUTF8StringEncoding]];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager.requestSerializer setAuthorizationHeaderFieldWithUsername:@"moinsam" password:@"cheese"];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
AFHTTPRequestOperation *operation = [manager HTTPRequestOperationWithRequest:request success:<block> failure:<block>];
This is size improvement of cmlevy answer - try
<input type=file oninput="pic.src=window.URL.createObjectURL(this.files[0])">
<img id="pic" />
_x000D_
In your example propertyInfo.GetValue(this, null)
should work. Consider altering GetNamesAndTypesAndValues()
as follows:
public void GetNamesAndTypesAndValues()
{
foreach (PropertyInfo propertyInfo in allClassProperties)
{
Console.WriteLine("{0} [type = {1}] [value = {2}]",
propertyInfo.Name,
propertyInfo.PropertyType,
propertyInfo.GetValue(this, null));
}
}
The second parameter of findBy
is for ORDER.
$ens = $em->getRepository('AcmeBinBundle:Marks')
->findBy(
array('type'=> 'C12'),
array('id' => 'ASC')
);
This is more complex than some other solutions, but may offer more flexibility in scenarios:
1) Make a class definition to isolate (encapsulate) the styling you want to apply/remove selectively. It can be empty (and for this case, probably should be):
.myColor {}
2) use this code, based on http://jsfiddle.net/kdp5V/167/ from this answer by gilly3:
function changeCSSRule(styleSelector,property,value) {
for (var ssIdx = 0; ssIdx < document.styleSheets.length; ssIdx++) {
var ss = document.styleSheets[ssIdx];
var rules = ss.cssRules || ss.rules;
if(rules){
for (var ruleIdx = 0; ruleIdx < rules.length; ruleIdx++) {
var rule = rules[ruleIdx];
if (rule.selectorText == styleSelector) {
if(typeof value == 'undefined' || !value){
rule.style.removeProperty(property);
} else {
rule.style.setProperty(property,value);
}
return; // stops at FIRST occurrence of this styleSelector
}
}
}
}
}
Usage example: http://jsfiddle.net/qvkwhtow/
Caveats:
Isolating the styling this way is what CSS is all about, even if manipulating it isn't. Manipulating CSS rules is NOT what jQuery is all about, jQuery manipulates DOM elements, and uses CSS selectors to do it.
You can also do the following,to import datetime
from datetime import datetime as dt
dt.strptime(date, '%Y-%m-%d')
To count unique non-integers - similar to Eelco Hoogendoorn's answer but considerably faster (factor of 5 on my machine), I used weave.inline
to combine numpy.unique
with a bit of c-code;
import numpy as np
from scipy import weave
def count_unique(datain):
"""
Similar to numpy.unique function for returning unique members of
data, but also returns their counts
"""
data = np.sort(datain)
uniq = np.unique(data)
nums = np.zeros(uniq.shape, dtype='int')
code="""
int i,count,j;
j=0;
count=0;
for(i=1; i<Ndata[0]; i++){
count++;
if(data(i) > data(i-1)){
nums(j) = count;
count = 0;
j++;
}
}
// Handle last value
nums(j) = count+1;
"""
weave.inline(code,
['data', 'nums'],
extra_compile_args=['-O2'],
type_converters=weave.converters.blitz)
return uniq, nums
Profile info
> %timeit count_unique(data)
> 10000 loops, best of 3: 55.1 µs per loop
Eelco's pure numpy
version:
> %timeit unique_count(data)
> 1000 loops, best of 3: 284 µs per loop
Note
There's redundancy here (unique
performs a sort also), meaning that the code could probably be further optimized by putting the unique
functionality inside the c-code loop.
The Pumping lemma for regular languages is the reason why you can't do that.
The generated automaton will have a finite number of states, say k, so a string of k+1 opening braces is bound to have a state repeated somewhere (as the automaton processes the characters). The part of the string between the same state can be duplicated infinitely many times and the automaton will not know the difference.
In particular, if it accepts k+1 opening braces followed by k+1 closing braces (which it should) it will also accept the pumped number of opening braces followed by unchanged k+1 closing brases (which it shouldn't).
If you want, you can use the "define" function, but this function creates a constant which can't be changed once defined.
<?php
define("GREETING", "Welcome to W3Schools.com!");
function myTest() {
echo GREETING;
}
myTest();
?>
I have the similar problem, but with IntelliJ IDEA + Maven + TestNG + spring-test. (spring-test is essential of course :) ) It was fixed when I've change config of maven-surefire-plugin to disable run tests in parallel. Like this:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.9</version>
<configuration>
<skipTests>${maven.test.skip}</skipTests>
<trimStackTrace>false</trimStackTrace>
<!--<parallel>methods</parallel>-->
<!-- to skip integration tests -->
<excludes>
<exclude>**/IT*Test.java</exclude>
<exclude>**/integration/*Test.java</exclude>
</excludes>
</configuration>
<executions>
<execution>
<id>integration-test</id>
<phase>integration-test</phase>
<goals>
<goal>test</goal>
</goals>
<configuration>
<skipTests>${maven.integration-test.skip}</skipTests>
<!-- Make sure to include this part, since otherwise it is excluding Integration tests -->
<excludes>
<exclude>none</exclude>
</excludes>
<includes>
<include>**/IT*Test.java</include>
<include>**/integration/*Test.java</include>
</includes>
</configuration>
</execution>
</executions>
</plugin>
I don't know if this will help, but I did this:
LocationManager locationManager = (LocationManager) context.getSystemService(context.LOCATION_SERVICE);
Unless this is a one-off data conversion, chances are you will benefit from using a calendar table.
Having such a table makes it really easy to filter or aggregate data for non-standard periods in addition to regular ISO weeks. Weeks usually behave a bit differently across companies and the departments within them. As soon as you leave "ISO-land" the built-in date functions can't help you.
create table calender(
day date not null -- Truncated date
,iso_year_week number(6) not null -- ISO Year week (IYYYIW)
,retail_week number(6) not null -- Monday to Sunday (YYYYWW)
,purchase_week number(6) not null -- Sunday to Saturday (YYYYWW)
,primary key(day)
);
You can either create additional tables for "purchase_weeks" or "retail_weeks", or simply aggregate on the fly:
select a.colA
,a.colB
,b.first_day
,b.last_day
from your_table_with_weeks a
join (select iso_year_week
,min(day) as first_day
,max(day) as last_day
from calendar
group
by iso_year_week
) b on(a.iso_year_week = b.iso_year_week)
If you process a large number of records, aggregating on the fly won't make a noticable difference, but if you are performing single-row you would benefit from creating tables for the weeks as well.
Using calendar tables provides a subtle performance benefit in that the optimizer can provide better estimates on static columns than on nested add_months(to_date(to_char()))
function calls.
Python strings are immutable and hence have more complex handling when talking about its operations. Note that a string with spaces is actually an empty string but has a non-zero size. Let’s see two different methods of checking if string is empty or not: Method #1 : Using Len() Using Len() is the most generic method to check for zero-length string. Even though it ignores the fact that a string with just spaces also should be practically considered as an empty string even its non-zero.
Method #2 : Using not
Not operator can also perform the task similar to Len(), and checks for 0 length string, but same as the above, it considers the string with just spaces also to be non-empty, which should not practically be true.
Good Luck!
I know this is a bit old but the answer in short would be <load-on-startup> both occurrences have given the same id which is 1 twice. This may confuse loading sequence.
I also had a similar exception when debugging in Eclipse. When I moused-over an object, the pop up box displayed an com.sun.jdi.InvocationException
message. The root cause for me was not the toString()
method of my class, but rather the hashCode()
method. It was causing a NullPointerException
, which caused the com.sun.jdi.InvocationException
to appear during debugging. Once I took care of the null pointer, everything worked as expected.
SLaks has the right answer... but let me be a bit more specific for people, like me, who are annoyed by this and can't find it right away :
Project -> Properties -> Application -> Target Framework -> select ".Net Framework 4"
the project will then save and reload.
There is no need to install Anaconda again. Conda, the package manager for Anaconda, fully supports separated environments. The easiest way to create an environment for Python 2.7 is to do
conda create -n python2 python=2.7 anaconda
This will create an environment named python2
that contains the Python 2.7 version of Anaconda. You can activate this environment with
source activate python2
This will put that environment (typically ~/anaconda/envs/python2
) in front in your PATH
, so that when you type python
at the terminal it will load the Python from that environment.
If you don't want all of Anaconda, you can replace anaconda
in the command above with whatever packages you want. You can use conda
to install packages in that environment later, either by using the -n python2
flag to conda
, or by activating the environment.
The return statement
stops the execution of a function and returns a value
from that function.
While updating global variables is one way to pass information back to the code that called the function
, this is not an ideal way of doing so. A much better alternative is to write the function so that values that are used by the function are passed to it as parameters and the function returns whatever value that it needs to without using or updating any global variables
.
By limiting the way in which information is passed to and from functions we can make it easier to reuse the same function from multiple places in our code.
JavaScript provides for passing one value back to the code that called it after everything in the function that needs to run has finished running.
JavaScript passes a value from a function back to the code that called it by using the return statement
. The value to be returned is specified in the return
keyword.
In v2.0 of the Graph API, calling /me/friends
returns the person's friends who also use the app.
In addition, in v2.0, you must request the user_friends
permission from each user. user_friends
is no longer included by default in every login. Each user must grant the user_friends
permission in order to appear in the response to /me/friends
. See the Facebook upgrade guide for more detailed information, or review the summary below.
The /me/friendlists
endpoint and user_friendlists
permission are not what you're after. This endpoint does not return the users friends - its lets you access the lists a person has made to organize their friends. It does not return the friends in each of these lists. This API and permission is useful to allow you to render a custom privacy selector when giving people the opportunity to publish back to Facebook.
If you want to access a list of non-app-using friends, there are two options:
If you want to let your people tag their friends in stories that they publish to Facebook using your App, you can use the /me/taggable_friends
API. Use of this endpoint requires review by Facebook and should only be used for the case where you're rendering a list of friends in order to let the user tag them in a post.
If your App is a Game AND your Game supports Facebook Canvas, you can use the /me/invitable_friends
endpoint in order to render a custom invite dialog, then pass the tokens returned by this API to the standard Requests Dialog.
In other cases, apps are no longer able to retrieve the full list of a user's friends (only those friends who have specifically authorized your app using the user_friends
permission).
For apps wanting allow people to invite friends to use an app, you can still use the Send Dialog on Web or the new Message Dialog on iOS and Android.
Resumee of Richard Fearn's answer , to make each second line gray:
jTable.setDefaultRenderer(Object.class, new DefaultTableCellRenderer()
{
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
{
final Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
c.setBackground(row % 2 == 0 ? Color.LIGHT_GRAY : Color.WHITE);
return c;
}
});
Ready-to-use solution:
public class GoogleServicesUtils {
public static void openAppInGooglePlay(Context context) {
final String appPackageName = context.getPackageName();
try {
context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appPackageName)));
} catch (android.content.ActivityNotFoundException e) { // if there is no Google Play on device
context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + appPackageName)));
}
}
}
Based on Eric's answer.
Note : To allow the ngModel exists Independently inside reactive form, we have to use ngModelOptions as follows:
[ngModelOptions]="{ standalone: true }"
For Example :
<mat-form-field appearance="outline" class="w-100">
<input
matInput
[(ngModel)]="accountType"
[ngModelOptions]="{ standalone: true }"
/>
</mat-form-field>
Click on Wamp icon and open Apache/httpd.conf and search "#LoadModule rewrite_module modules/mod_rewrite.so". Remove # as below and save it
LoadModule rewrite_module modules/mod_rewrite.so
and restart all service.
Code like "a => b" means, for an associative array (some languages, like Perl, if I remember correctly, call those "hash"), that 'a' is a key, and 'b' a value.
You might want to take a look at the documentations of, at least:
Here, you are having an array, called $user_list
, and you will iterate over it, getting, for each line, the key of the line in $user
, and the corresponding value in $pass
.
For instance, this code:
$user_list = array(
'user1' => 'password1',
'user2' => 'password2',
);
foreach ($user_list as $user => $pass)
{
var_dump("user = $user and password = $pass");
}
Will get you this output:
string 'user = user1 and password = password1' (length=37)
string 'user = user2 and password = password2' (length=37)
(I'm using var_dump
to generate a nice output, that facilitates debuging; to get a normal output, you'd use echo
)
"Equal or greater" is the other way arround: "greater or equals", which is written, in PHP, like this; ">="
The Same thing for most languages derived from C: C++, JAVA, PHP, ...
As a piece of advice: If you are just starting with PHP, you should definitely spend some time (maybe a couple of hours, maybe even half a day or even a whole day) going through some parts of the manual :-)
It'd help you much!
following won't work
echo $(awk '{awk code}' file) > file
this should work
echo "$(awk '{awk code}' file)" > file
as System environment Variable:
Windows:
Start -> type "envi" select environment variables and add a new:
Name: spring_profiles_active
Value: dev
(or whatever yours is)
Linux: add following line to /etc/environment under PATH:
spring_profiles_active=prod
(or whatever profile is)
then also export spring_profiles_active=prod
so you have it in the runtime now.
You can use the static/class constructor to initialize your dictionary:
public static class ErrorCode
{
public const IDictionary<string, string> ErrorCodeDic;
public static ErrorCode()
{
ErrorCodeDic = new Dictionary<string, string>()
{ {"1", "User name or password problem"} };
}
}
you can use the Utility mettod. Arrays.deeptoString();
public static void main(String[] args) {
int twoD[][] = new int[4][];
twoD[0] = new int[1];
twoD[1] = new int[2];
twoD[2] = new int[3];
twoD[3] = new int[4];
System.out.println(Arrays.deepToString(twoD));
}
link your currentily folders to vscode.
Windows Registry Editor Version 5.00
; Directory\Background\shell => on empty space
[HKEY_CLASSES_ROOT\Directory\Background\shell\vscode]
"Icon"="C:\\current-folder-vscode\\Code.exe,0"
@="VsCode"
[HKEY_CLASSES_ROOT\Directory\Background\shell\vscode\command]
@="C:\\current-folder-vscode\\Code.exe ."
; Directory\shell => on a folder
[HKEY_CLASSES_ROOT\Directory\shell\vscode]
@="VsCode"
"Icon"="C:\\current-folder-vscode\\Code.exe,0"
[HKEY_CLASSES_ROOT\Directory\shell\vscode\command]
@="C:\\current-folder-vscode\\Code.exe ."
Another simple one-liner that hasn't been mentioned here:
value = line.split("Path=", 1)[-1]
This will also work properly for various edge cases:
>>> print("prefixfoobar".split("foo", 1)[-1])
"bar"
>>> print("foofoobar".split("foo", 1)[-1])
"foobar"
>>> print("foobar".split("foo", 1)[-1])
"bar"
>>> print("bar".split("foo", 1)[-1])
"bar"
>>> print("".split("foo", 1)[-1])
""
Working code, I have used Java Mail 1.4.7 jar
import java.util.Properties;
import javax.activation.*;
import javax.mail.*;
public class MailProjectClass {
public static void main(String[] args) {
final String username = "[email protected]";
final String password = "your.password";
Properties props = new Properties();
props.put("mail.smtp.auth", true);
props.put("mail.smtp.starttls.enable", true);
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("[email protected]"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("[email protected]"));
message.setSubject("Testing Subject");
message.setText("PFA");
MimeBodyPart messageBodyPart = new MimeBodyPart();
Multipart multipart = new MimeMultipart();
String file = "path of file to be attached";
String fileName = "attachmentName";
DataSource source = new FileDataSource(file);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(fileName);
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
System.out.println("Sending");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
I found this solution helpful. Just subtract if it isn't monday to get the previous Monday. I am using $lower_date as the date I pulled from a query that I then need to reconcile to the previous Monday.
//set this up to go backwards until you find monday
while(date('D',strtotime($lower_date))!='Mon'){
$lower_date = date('Y-m-d', strtotime($lower_date . ' - 1 day')); //increase the upper spec
}
Here are two quickie approaches I know of:
In base
AQ1 <- airquality
AQ1[is.na(AQ1 <- airquality)] <- 0
AQ1
Not in base
library(qdap)
NAer(airquality)
PS P.S. Does my command above create a new dataframe called AQ1?
Look at AQ1 and see
Just open your terminal and run this command thats for windows users
pip install -U wxPython
for Ubuntu user you can use this
pip install -U \
-f https://extras.wxpython.org/wxPython4/extras/linux/gtk3/ubuntu-16.04 \
wxPython
First set
[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
Go to your AppDelegate, find itsdidFinishLaunchingWithOptions
method and do:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
}
and then set View controller-based status bar appearance
equal to NO in plist.
If you have installed VS2012 as well, the old cvtres file will no longer work.
Try removing the file (I simply renamed):
C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\BIN\cvtres.exe
You can also debug using the /VERBOSE linker option in order to get more information regarding the linker error. There you should see an error message that the invoke to cvtres fails.
In my case, I was using Laravel 5 and I had forgotten to change the mail globals in the .env file that is located in your directory root folder (these variables override your mail configuration)
MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=465
[email protected]
MAIL_PASSWORD=yourpassword
by default, the mailhost is:
MAIL_HOST=mailtraper.io
I was getting the same error but that worked for me.
COUNTIF
function can count cell which specific condition
where as COUNTA
will count all cell which contain any value
Example: Function in A7
: =COUNTA(A1:A6)
Range:
A1| a
A2| b
A3| banana
A4| 42
A5|
A6|
A7| 4 (result)
I generally store my macros in xlam
add-ins separately from my workbooks so I wanted to open a workbook and then run a macro stored separately.
Since this required a VBS Script, I wanted to make it "portable" so I could use it by passing arguments. Here is the final script, which takes 3 arguments.
I tested it like so:
"C:\Temp\runmacro.vbs" "C:\Temp\Book1.xlam" "Hello"
"C:\Temp\runmacro.vbs" "C:\Temp\Book1.xlsx" "Hello" "%AppData%\Microsoft\Excel\XLSTART\Book1.xlam"
runmacro.vbs:
Set args = Wscript.Arguments
ws = WScript.Arguments.Item(0)
macro = WScript.Arguments.Item(1)
If wscript.arguments.count > 2 Then
macrowb= WScript.Arguments.Item(2)
End If
LaunchMacro
Sub LaunchMacro()
Dim xl
Dim xlBook
Set xl = CreateObject("Excel.application")
Set xlBook = xl.Workbooks.Open(ws, 0, True)
If wscript.arguments.count > 2 Then
Set macrowb= xl.Workbooks.Open(macrowb, 0, True)
End If
'xl.Application.Visible = True ' Show Excel Window
xl.Application.run macro
'xl.DisplayAlerts = False ' suppress prompts and alert messages while a macro is running
'xlBook.saved = True ' suppresses the Save Changes prompt when you close a workbook
'xl.activewindow.close
xl.Quit
End Sub
SELECT @variable1 = col1, @variable2 = col2
FROM table1
You can allow the Docker user (here: root) to access the X11 display:
XSOCK=/tmp/.X11-unix
xhost +SI:localuser:root
docker run -t -i --rm -v $XSOCK:$XSOCK:ro -e DISPLAY=unix$(DISPLAY) image
xhost -SI:localuser:root
You don't need to compile python for Mac/Windows/Linux. It is an interpreted language, so you simply need to have the Python interpreter installed on the system of your choice (it is available for all three platforms).
As for a GUI library that works cross platform, Python's Tk/Tcl widget library works very well, and I believe is sufficiently cross platform.
Tkinter is the python interface to Tk/Tcl
From the python project webpage:
Tkinter is not the only GuiProgramming toolkit for Python. It is however the most commonly used one, and almost the only one that is portable between Unix, Mac and Windows
runAllManagedModulesForAllRequests=true
is actually a real bad solution. This increased the load time of my application by 200%. The better solution is to manually remove and add the session object and to avoid the run all managed modules attribute all together.
The way to go with javascript:
var data = new FormData();
$.each($("input[type='file']")[0].files, function(i, file) {
data.append('file', file);
});
$.ajax({
type: 'POST',
url: '/your/url',
cache: false,
contentType: false,
processData: false,
data : data,
success: function(result){
console.log(result);
},
error: function(err){
console.log(err);
}
})
If you call data.append('file', file) multiple times your request will contain an array of your files.
"The
append()
method of theFormData
interface appends a new value onto an existing key inside aFormData
object, or adds the key if it does not already exist. The difference betweenFormData.se
t andappend()
is that if the specified key already exists,FormData.set
will overwrite all existing values with the new one, whereasappend()
will append the new value onto the end of the existing set of values."
Myself using node.js and multipart handler middleware multer get the data as follows:
router.post('/trip/save', upload.array('file', 10), function(req, res){
// Your array of files is in req.files
}
you can use as.matrix as below:
output <- as.matrix(z)
function insSubstr($str, $sub, $posStart, $posEnd){
return mb_substr($str, 0, $posStart) . $sub . mb_substr($str, $posEnd + 1);
}
iText is the best library I know. Originally written in Java, there is a .NET port as well.
//Data Table
protected DataTable tblDynamic
{
get
{
return (DataTable)ViewState["tblDynamic"];
}
set
{
ViewState["tblDynamic"] = value;
}
}
//DynamicReport_GetUserType() function for getting data from DB
System.Data.DataSet ds = manage.DynamicReport_GetUserType();
tblDynamic = ds.Tables[13];
//Add Column as "TypeName"
tblDynamic.Columns.Add(new DataColumn("TypeName", typeof(string)));
//fill column data against ds.Tables[13]
for (int i = 0; i < tblDynamic.Rows.Count; i++)
{
if (tblDynamic.Rows[i]["Type"].ToString()=="A")
{
tblDynamic.Rows[i]["TypeName"] = "Apple";
}
if (tblDynamic.Rows[i]["Type"].ToString() == "B")
{
tblDynamic.Rows[i]["TypeName"] = "Ball";
}
if (tblDynamic.Rows[i]["Type"].ToString() == "C")
{
tblDynamic.Rows[i]["TypeName"] = "Cat";
}
if (tblDynamic.Rows[i]["Type"].ToString() == "D")
{
tblDynamic.Rows[i]["TypeName"] = "Dog;
}
}