SELECT
p.spid, p.status, p.hostname, p.loginame, p.cpu, r.start_time, t.text
FROM
sys.dm_exec_requests as r,
master.dbo.sysprocesses as p
CROSS APPLY sys.dm_exec_sql_text(p.sql_handle) t
WHERE
p.status NOT IN ('sleeping', 'background')
AND r.session_id = p.spid
And
KILL @spid
You can use __halt_compiler
function which will Halt the compiler execution
go
create proc GetEmail
@name varchar(22),
@gmail varchar(22)
as
begin
declare @a varchar(22)
set select @a=substring(@gmail,charindex('@',@gmail),len(@gmail)-charindex('@',@gmail)+1)
if (@a = 'gmail.com)
insert into table_name values(@name,@gmail)
else
print 'please enter valid email address'
end
if u got still no access to db, 1. in ur error message is set no password right? then first do mysqlpasswd 'username' after that enter and then give it a password type again as requested and then try to access again with mysql -p if you are root
You're not reading the file content:
my_file_contents = f.read()
See the docs for further infos
You could, without calling read()
or readlines()
loop over your file object:
f = open('goodlines.txt')
for line in f:
print(line)
If you want a list out of it (without \n
as you asked)
my_list = [line.rstrip('\n') for line in f]
Suffered from exact issue. Problem was because of NameValueSectionHandler in .config file. You should use AppSettingsSection instead:
<configuration>
<configSections>
<section name="DEV" type="System.Configuration.AppSettingsSection" />
<section name="TEST" type="System.Configuration.AppSettingsSection" />
</configSections>
<TEST>
<add key="key" value="value1" />
</TEST>
<DEV>
<add key="key" value="value2" />
</DEV>
</configuration>
then in C# code:
AppSettingsSection section = (AppSettingsSection)ConfigurationManager.GetSection("TEST");
btw NameValueSectionHandler is not supported any more in 2.0.
another solution will be to grab the text inside the title
tag & then use .html()
method of jQuery to construct the content of the tooltip.
$(function() {
$(document).tooltip({
position: {
using: function(position, feedback) {
$(this).css(position);
var txt = $(this).text();
$(this).html(txt);
$("<div>")
.addClass("arrow")
.addClass(feedback.vertical)
.addClass(feedback.horizontal)
.appendTo(this);
}
}
});
});
Yes, that is one way to get the first line of output from a command.
If the command outputs anything to standard error that you would like to capture in the same manner, you need to redirect the standard error of the command to the standard output stream:
utility 2>&1 | head -n 1
There are many other ways to capture the first line too, including sed 1q
(quit after first line), sed -n 1p
(only print first line, but read everything), awk 'FNR == 1'
(only print first line, but again, read everything) etc.
Have you tried using the replaceAll method to replace any occurence of \n or \r with the empty String?
For some reason in Angular 6 simply importing the FormsModule did not fix my issue. What finally fixed my issue was by adding
import { CommonModule } from '@angular/common';
@NgModule({
imports: [CommonModule],
})
export class MyClass{
}
Read the Advanced Bash-Scripting Guide Chapter 19. Here Documents.
Here's an example which will write the contents to a file at /tmp/yourfilehere
cat << EOF > /tmp/yourfilehere
These contents will be written to the file.
This line is indented.
EOF
Note that the final 'EOF' (The LimitString
) should not have any whitespace in front of the word, because it means that the LimitString
will not be recognized.
In a shell script, you may want to use indentation to make the code readable, however this can have the undesirable effect of indenting the text within your here document. In this case, use <<-
(followed by a dash) to disable leading tabs (Note that to test this you will need to replace the leading whitespace with a tab character, since I cannot print actual tab characters here.)
#!/usr/bin/env bash
if true ; then
cat <<- EOF > /tmp/yourfilehere
The leading tab is ignored.
EOF
fi
If you don't want to interpret variables in the text, then use single quotes:
cat << 'EOF' > /tmp/yourfilehere
The variable $FOO will not be interpreted.
EOF
To pipe the heredoc through a command pipeline:
cat <<'EOF' | sed 's/a/b/'
foo
bar
baz
EOF
Output:
foo
bbr
bbz
... or to write the the heredoc to a file using sudo
:
cat <<'EOF' | sed 's/a/b/' | sudo tee /etc/config_file.conf
foo
bar
baz
EOF
Here is a solution that takes into account different ports and https:
$pageURL = (@$_SERVER['HTTPS'] == 'on') ? 'https://' : 'http://';
if ($_SERVER['SERVER_PORT'] != '80')
$pageURL .= $_SERVER['SERVER_NAME'].':'.$_SERVER['SERVER_PORT'].$_SERVER['PHP_SELF'];
else
$pageURL .= $_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF'];
Or a more basic solution that does not take other ports into account:
$pageURL = (@$_SERVER['HTTPS'] == 'on') ? 'https://' : 'http://';
$pageURL .= $_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF'];
We have new technology for this problem: the java.time framework built into Java 8 and later.
Your input string is in standard ISO 8601 format. That standard is used by default in the java.time classes for parsing/generating textual representations of date-time values.
OffsetDateTime odt = OffsetDateTime.parse( "2012-10-01T09:45:00.000+02:00" );
Your Question suggests you want to truncate to a whole second.
OffsetDateTime odtTruncatedToWholeSecond = odt.truncatedTo( ChronoUnit.SECONDS );
It seems you want to omit the offset and time zone info. The pre-defined formatter DateTimeFormatter.ISO_LOCAL_DATE_TIME
does that.
And apparently you want to use a space in the middle rather than the standard T
. You could define your own formatter for this, but I would just do a string manipulation to replace the T
with a SPACE.
String output = odtTruncatedToWholeSecond.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME ).replace( "T" , " " );
As the comments on the Question suggest, strictly speaking you can accomplish your goal by working only with strings and not converting to any date-time objects. But I provide this Answer here assuming you may have other business logic to work with these date-time values.
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
Starting from tslint v5.8.0
you can set an exclude
property under your linterOptions
key in your tslint.json
file:
{
"extends": "tslint:latest",
"linterOptions": {
"exclude": [
"bin",
"**/__test__",
"lib/*generated.js"
]
}
}
More information on this here.
>>> class A(object): pass
>>> e = A()
>>> e
<__main__.A object at 0xb6d464ec>
>>> print type(e)
<class '__main__.A'>
>>> print type(e).__name__
A
>>>
what do you mean by convert into a string? you can define your own repr and str_ methods:
>>> class A(object):
def __repr__(self):
return 'hei, i am A or B or whatever'
>>> e = A()
>>> e
hei, i am A or B or whatever
>>> str(e)
hei, i am A or B or whatever
or i dont know..please add explainations ;)
What about a wrapper around your existing code:
public Collection<File> getMatchingFiles( String directory, String extension ) {
return new ArrayList<File>()(
getAllFilesThatMatchFilenameExtension( directory, extension ) );
}
I will throw a warning though. If you can live with that warning, then you're done.
public static void main(String[] args) {
char[] str = { 'a', 'b', 'a','b','c','e','c' };
for (int i = 1; i < str.length; i++) {
for (int j = 0; j < i; j++) {
if (str[i] == str[j]) {
str[i] = ' ';
}
}
}
System.out.println(str);
}
This is an old question so I don't see a Java 8 equivalent. Here is an example for this specific case.
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* Compares multiple parts of the Report object.
*/
public class SimpleJava8ComparatorClass {
public static void main(String[] args) {
List<Report> reportList = new ArrayList<>();
reportList.add(new Report("reportKey2", "studentNumber2", "school1"));
reportList.add(new Report("reportKey4", "studentNumber4", "school6"));
reportList.add(new Report("reportKey1", "studentNumber1", "school1"));
reportList.add(new Report("reportKey3", "studentNumber2", "school4"));
reportList.add(new Report("reportKey2", "studentNumber2", "school3"));
System.out.println("pre-sorting");
System.out.println(reportList);
System.out.println();
Collections.sort(reportList, Comparator.comparing(Report::getReportKey)
.thenComparing(Report::getStudentNumber)
.thenComparing(Report::getSchool));
System.out.println("post-sorting");
System.out.println(reportList);
}
private static class Report {
private String reportKey;
private String studentNumber;
private String school;
public Report(String reportKey, String studentNumber, String school) {
this.reportKey = reportKey;
this.studentNumber = studentNumber;
this.school = school;
}
public String getReportKey() {
return reportKey;
}
public void setReportKey(String reportKey) {
this.reportKey = reportKey;
}
public String getStudentNumber() {
return studentNumber;
}
public void setStudentNumber(String studentNumber) {
this.studentNumber = studentNumber;
}
public String getSchool() {
return school;
}
public void setSchool(String school) {
this.school = school;
}
@Override
public String toString() {
return "Report{" +
"reportKey='" + reportKey + '\'' +
", studentNumber='" + studentNumber + '\'' +
", school='" + school + '\'' +
'}';
}
}
}
Sure. Here's a completely silly program that demonstrates calling main
recursively.
public class main
{
public static void main(String[] args)
{
for (int i = 0; i < args.length; ++i)
{
if (args[i] != "")
{
args[i] = "";
System.out.println((args.length - i) + " left");
main(args);
}
}
}
}
Check the documentation of sql_mode
Method 1:
Check default value of sql_mode:
SELECT @@sql_mode //check current value for sql_mode
SET GLOBAL sql_mode = "NO_BACKSLASH_ESCAPES,STRICT_TRANS_TABLE,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION";
Method 2:
Access phpmyadmin for editing your sql_mode
Restart server after executing above things
Using Vim, it shouldn't be more involved than hitting Esc, and then typing...
:%s/\t/ /g
...on the file you want to change. That will convert all tabs to four spaces. If you have inconsistent spacing as well, then that will be more difficult.
read.table
wants to return a data.frame
, which must have an element in each column. Therefore R expects each row to have the same number of elements and it doesn't fill in empty spaces by default. Try read.table("/PathTo/file.csv" , fill = TRUE )
to fill in the blanks.
e.g.
read.table( text= "Element1 Element2
Element5 Element6 Element7" , fill = TRUE , header = FALSE )
# V1 V2 V3
#1 Element1 Element2
#2 Element5 Element6 Element7
A note on whether or not to set header = FALSE
... read.table
tries to automatically determine if you have a header row thus:
header
is set toTRUE
if and only if the first row contains one fewer field than the number of columns
You can use math.ceil()
to round up, and then multiply by 10
import math
def roundup(x):
return int(math.ceil(x / 10.0)) * 10
To use just do
>>roundup(45)
50
In case your data are stored as a Pandas DataFrame
, you can use remove_stopwords
from textero that use the NLTK stopwords list by default.
import pandas as pd
import texthero as hero
df['text_without_stopwords'] = hero.remove_stopwords(df['text'])
A simple code for this will be
time = time.split(':');// here the time is like "16:14"
let meridiemTime = time[0] >= 12 && (time[0]-12 || 12) + ':' + time[1] + ' PM' || (Number(time[0]) || 12) + ':' + time[1] + ' AM';
You can adjust according to your time format
CASE might help you out:
SELECT t.first_name,
t.last_name,
t.employid,
t.status
FROM employeetable t
WHERE t.status = (CASE WHEN status_flag = STATUS_ACTIVE THEN 'A'
WHEN status_flag = STATUS_INACTIVE THEN 'T'
ELSE null END)
AND t.business_unit = (CASE WHEN source_flag = SOURCE_FUNCTION THEN 'production'
WHEN source_flag = SOURCE_USER THEN 'users'
ELSE null END)
AND t.first_name LIKE firstname
AND t.last_name LIKE lastname
AND t.employid LIKE employeeid;
The CASE statement evaluates multiple conditions to produce a single value. So, in the first usage, I check the value of status_flag, returning 'A', 'T' or null depending on what it's value is, and compare that to t.status. I do the same for the business_unit column with a second CASE statement.
Use this instead:
$('#save').click(function () {
$('#mytable').find('input[type="checkbox"]:checked') //...
});
Let me explain you what the selector does:
input[type="checkbox"]
means that this will match each <input />
with type attribute type
equals to checkbox
After that: :checked
will match all checked checkboxes.
You can loop over these checkboxes with:
$('#save').click(function () {
$('#mytable').find('input[type="checkbox"]:checked').each(function () {
//this is the current checkbox
});
});
Here is demo in JSFiddle.
And here is a demo which solves exactly your problem http://jsfiddle.net/DuE8K/1/.
$('#save').click(function () {
$('#mytable').find('tr').each(function () {
var row = $(this);
if (row.find('input[type="checkbox"]').is(':checked') &&
row.find('textarea').val().length <= 0) {
alert('You must fill the text area!');
}
});
});
Primitive data type
The primitive data type is a basic type provided by a programming language as a basic building block. So it's predefined data types. A primitive type has always a value. It storing simple value.
It specifies the size and type of variable values, so the size of a primitive type depends on the data type and it has no additional methods.
And these are reserved keywords in the language. So we can't use these names as variable, class or method name. A primitive type starts with a lowercase letter. When declaring the primitive types we don't need to allocate memory. (memory is allocated and released by JRE-Java Runtime Environment in Java)
+================+=========+===================================================================================+
| Primitive type | Size | Description |
+================+=========+===================================================================================+
| byte | 1 byte | Stores whole numbers from -128 to 127 |
+----------------+---------+-----------------------------------------------------------------------------------+
| short | 2 bytes | Stores whole numbers from -32,768 to 32,767 |
+----------------+---------+-----------------------------------------------------------------------------------+
| int | 4 bytes | Stores whole numbers from -2,147,483,648 to 2,147,483,647 |
+----------------+---------+-----------------------------------------------------------------------------------+
| long | 8 bytes | Stores whole numbers from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 |
+----------------+---------+-----------------------------------------------------------------------------------+
| float | 4 bytes | Stores fractional numbers. Sufficient for storing 6 to 7 decimal digits |
+----------------+---------+-----------------------------------------------------------------------------------+
| double | 8 bytes | Stores fractional numbers. Sufficient for storing 15 decimal digits |
+----------------+---------+-----------------------------------------------------------------------------------+
| char | 2 bytes | Stores a single character/letter or ASCII values |
+----------------+---------+-----------------------------------------------------------------------------------+
| boolean | 1 bit | Stores true or false values |
+----------------+---------+-----------------------------------------------------------------------------------+
Reference data type
Reference data type refers to objects. Most of these types are not defined by programming language(except for String, arrays in JAVA). Reference types of value can be null. It storing an address of the object it refers to. Reference or non-primitive data types have all the same size. and reference types can be used to call methods to perform certain operations.
when declaring the reference type need to allocate memory. In Java, we used new
keyword to allocate memory, or alternatively, call a factory method.
Example:
List< String > strings = new ArrayList<>() ; // Calling `new` to instantiate an object and thereby allocate memory.
Point point = Point(1,2) ; // Calling a factory method.
You can use docker-compose run
instead of docker-compose up
and tack the arguments on the end. For example:
docker-compose run dperson/samba arg1 arg2 arg3
If you need to connect to other docker containers, use can use --service-ports
option:
docker-compose run --service-ports dperson/samba arg1 arg2 arg3
This occurs typically when the stmt is reused butexpecting a different ResultSet, try creting a new stmt and executeQuery. It fixed it for me!
Your code works for me. Here is my test case:
mysql> CREATE TABLE carmake (country ENUM('Canada', 'United States'));
Query OK, 0 rows affected (0.00 sec)
mysql> SHOW CREATE TABLE carmake;
+---------+-------------------------------------------------------------------------------------------------------------------------+
| Table | Create Table |
+---------+-------------------------------------------------------------------------------------------------------------------------+
| carmake | CREATE TABLE `carmake` (
`country` enum('Canada','United States') default NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1 |
+---------+-------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)
mysql> ALTER TABLE carmake CHANGE country country ENUM('Sweden','Malaysia');
Query OK, 0 rows affected (0.53 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> SHOW CREATE TABLE carmake;
+---------+--------------------------------------------------------------------------------------------------------------------+
| Table | Create Table |
+---------+--------------------------------------------------------------------------------------------------------------------+
| carmake | CREATE TABLE `carmake` (
`country` enum('Sweden','Malaysia') default NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1 |
+---------+--------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)
What error are you seeing?
FWIW this would also work:
ALTER TABLE carmake MODIFY COLUMN country ENUM('Sweden','Malaysia');
I would actually recommend a country table rather than enum column. You may have hundreds of countries which would make for a rather large and awkward enum.
EDIT: Now that I can see your error message:
ERROR 1265 (01000): Data truncated for column 'country' at row 1.
I suspect you have some values in your country column that do not appear in your ENUM
. What is the output of the following command?
SELECT DISTINCT country FROM carmake;
ANOTHER EDIT: What is the output of the following command?
SHOW VARIABLES LIKE 'sql_mode';
Is it STRICT_TRANS_TABLES
or STRICT_ALL_TABLES
? That could lead to an error, rather than the usual warning MySQL would give you in this situation.
YET ANOTHER EDIT: Ok, I now see that you definitely have values in the table that are not in the new ENUM
. The new ENUM
definition only allows 'Sweden'
and 'Malaysia'
. The table has 'USA'
, 'India'
and several others.
LAST EDIT (MAYBE): I think you're trying to do this:
ALTER TABLE carmake CHANGE country country ENUM('Italy', 'Germany', 'England', 'USA', 'France', 'South Korea', 'Australia', 'Spain', 'Czech Republic', 'Sweden', 'Malaysia') DEFAULT NULL;
Here is a simple routine for an array of primitive elements:
for ($i = 0; $i < count($mySimpleArray); $i++)
{
echo $mySimpleArray[$i] . "\n";
}
You are passing floats to a classifier which expects categorical values as the target vector. If you convert it to int
it will be accepted as input (although it will be questionable if that's the right way to do it).
It would be better to convert your training scores by using scikit's labelEncoder
function.
The same is true for your DecisionTree and KNeighbors qualifier.
from sklearn import preprocessing
from sklearn import utils
lab_enc = preprocessing.LabelEncoder()
encoded = lab_enc.fit_transform(trainingScores)
>>> array([1, 3, 2, 0], dtype=int64)
print(utils.multiclass.type_of_target(trainingScores))
>>> continuous
print(utils.multiclass.type_of_target(trainingScores.astype('int')))
>>> multiclass
print(utils.multiclass.type_of_target(encoded))
>>> multiclass
There is also an option to make configuration
static in startup.cs so that what you can access it anywhere with ease, static variables are convenient huh!
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
internal static IConfiguration Configuration { get; private set; }
This makes configuration accessible anywhere using Startup.Configuration.GetSection...
What can go wrong?
I would like to refer a previous question, Because I have faced same problem and solved by this solution.
First of all a constraint is always built with a Hash
value in it's name. So problem is this HASH
is varies in different Machine or Database. For example DF__Companies__IsGlo__6AB17FE4
here 6AB17FE4
is the hash value(8 bit). So I am referring a single script which will be fruitful to all
DECLARE @Command NVARCHAR(MAX)
declare @table_name nvarchar(256)
declare @col_name nvarchar(256)
set @table_name = N'ProcedureAlerts'
set @col_name = N'EmailSent'
select @Command ='Alter Table dbo.ProcedureAlerts Drop Constraint [' + ( select d.name
from
sys.tables t
join sys.default_constraints d on d.parent_object_id = t.object_id
join sys.columns c on c.object_id = t.object_id
and c.column_id = d.parent_column_id
where
t.name = @table_name
and c.name = @col_name) + ']'
--print @Command
exec sp_executesql @Command
It will drop your default constraint. However if you want to create it again you can simply try this
ALTER TABLE [dbo].[ProcedureAlerts] ADD DEFAULT((0)) FOR [EmailSent]
Finally, just simply run a DROP
command to drop the column.
If your textbox has an id attribute of "mytextbox", then you can get the length like this:
var myLength = $("#mytextbox").val().length;
$("#mytextbox")
finds the textbox by its id..val()
gets the value of the input element entered by the user, which is a string..length
gets the number of characters in the string.It looks like the SQL Server doesn't have permission to access file C:\backup.bak. I would check the permissions of the account that is assigned to the SQL Server service account.
As part of the solution, you may want to save your backup files to somewhere other that the root of the C: drive. That might be one reason why you are having permission problems.
Combining @Ramnath and @Tommy's answers allowed me to find an approach that works in base R for one or more columns.
Basic usage:
> df = data.frame(
+ id=1:3, foo=c('a|b','b|c','c|d'),
+ bar=c('p|q', 'r|s', 's|t'), stringsAsFactors=F)
> transform(df, test=do.call(rbind, strsplit(foo, '|', fixed=TRUE)), stringsAsFactors=F)
id foo bar test.1 test.2
1 1 a|b p|q a b
2 2 b|c r|s b c
3 3 c|d s|t c d
Multiple columns:
> transform(df, lapply(list(foo,bar),
+ function(x)do.call(rbind, strsplit(x, '|', fixed=TRUE))), stringsAsFactors=F)
id foo bar X1 X2 X1.1 X2.1
1 1 a|b p|q a b p q
2 2 b|c r|s b c r s
3 3 c|d s|t c d s t
Better naming of multiple split columns:
> transform(df, lapply({l<-list(foo,bar);names(l)=c('foo','bar');l},
+ function(x)do.call(rbind, strsplit(x, '|', fixed=TRUE))), stringsAsFactors=F)
id foo bar foo.1 foo.2 bar.1 bar.2
1 1 a|b p|q a b p q
2 2 b|c r|s b c r s
3 3 c|d s|t c d s t
If you're on OSX you can also find it your keychain. Your developer and distribution certificates have your Team ID in them.
Applications -> Utilities -> Keychain Access.
Under the 'login' Keychain, go into the 'Certificates' category.
Scroll to find your development or distribution certificate. They will read:
iPhone Distribution: Team Name (certificate id)
or
iPhone Developer: Team Name (certificate id)
Simply double-click on the item, and the
is the "Team ID"
Note that this is the only way to find your
You can not find the "Personal team" ID on the Apple web interface.
For example, if you are automating a build from say Unity, during development you'll want it to appear in Xcode as your "Personal team" - this is the only way to get that value.
You can find Largest and Third largest number of unsorted array as well.
public class ThirdLargestNumber {
public static void main(String[] args) {
int arr[] = { 220, 200, 100, 100, 300, 600, 50, 5000, 125, 785 };
int first = 0, second = 0, third = 0, firstTemp = 0, secondTemp = 0;
for (int i = 0; i <= 9 /*
* Length of array-1. You can use here length
* property of java array instead of hard coded
* value
*/; i++) {
if (arr[i] == first) {
continue;
}
if (arr[i] > first) {
firstTemp = first;
secondTemp = second;
first = arr[i];
second = firstTemp;
if (secondTemp > third) {
third = secondTemp;
}
} else {
if ((arr[i] == second) || (arr[i]) == first) {
continue;
}
if ((arr[i] > second) && (arr[i]) < first) {
secondTemp = second;
second = arr[i];
if (secondTemp > third) {
third = secondTemp;
}
} else {
if (arr[i] > third) {
third = arr[i];
}
}
}
}
// System.out.println("Third largest number: " + third);
System.out.println("Second largest number: " + second);
// System.out.println("Largest number: " + first);
}
}
Open up Settings (By default is Alt + Ctrl + S) and search for Live Templates. In the upper part there's an option that says "By default expand with TAB" (TAB is the default), choose "Custom" and then hit "change" and add the keymap "ctrl+spacebar" to the option "Expand Live Template/Emmet Abbreviation".
Now you can hit ctrl + spacebar and expand the live templates. Now, to change it to "syso" instead of "sout", in the Live Templates option, theres a list of tons of options checked, go to "other" and expand it, there you wil find "sout", just rename it to "syso" and hit aply.
Hope this can help you.
Use sed:
MYVAR=ho02123ware38384you443d34o3434ingtod38384day
echo "$MYVAR" | sed -e 's/[a-zA-Z]/X/g' -e 's/[0-9]/N/g'
# prints XXNNNNNXXXXNNNNNXXXNNNXNNXNNNNXXXXXXNNNNNXXX
Note that the subsequent -e
's are processed in order. Also, the g
flag for the expression will match all occurrences in the input.
You can also pick your favorite tool using this method, i.e. perl, awk, e.g.:
echo "$MYVAR" | perl -pe 's/[a-zA-Z]/X/g and s/[0-9]/N/g'
This may allow you to do more creative matches... For example, in the snip above, the numeric replacement would not be used unless there was a match on the first expression (due to lazy and
evaluation). And of course, you have the full language support of Perl to do your bidding...
This should help you
HTML
<!-- pretty much i just need to click a link within the regions table and it changes to the neccesary div. -->
<table>
<tr class="thumb"></tr>
<td><a href="#" class="showall">All Regions</a> (shows main map) (link)</td>
<tr class="thumb"></tr>
<td>Northern Region (link)</td>
</tr>
<tr class="thumb"></tr>
<td>Southern Region (link)</td>
</tr>
<tr class="thumb"></tr>
<td>Eastern Region (link)</td>
</tr>
</table>
<br />
<div id="mainmapplace">
<div id="mainmap">
All Regions image
</div>
</div>
<div id="region">
<div class="replace">northern image</div>
<div class="replace">southern image</div>
<div class="replace">Eastern image</div>
</div>
JavaScript
var originalmap;
var flag = false;
$(function (){
$(".replace").click(function(){
flag = true;
originalmap = $('#mainmap');
$('#mainmap').replaceWith($(this));
});
$('.showall').click(
function(){
if(flag == true){
$('#region').append($('#mainmapplace .replace'));
$('#mainmapplace').children().remove();
$('#mainmapplace').append($(originalmap));
//$('#mapplace').append();
}
}
)
})
CSS
#mainmapplace{
width: 100px;
height: 100px;
background: red;
}
#region div{
width: 100px;
height: 100px;
background: blue;
margin: 10px 0 0 0;
}
The wb
indicates that the file is opened for writing in binary mode.
When writing in binary mode, Python makes no changes to data as it is written to the file. In text mode (when the b
is excluded as in just w
or when you specify text mode with wt
), however, Python will encode the text based on the default text encoding. Additionally, Python will convert line endings (\n
) to whatever the platform-specific line ending is, which would corrupt a binary file like an exe
or png
file.
Text mode should therefore be used when writing text files (whether using plain text or a text-based format like CSV), while binary mode must be used when writing non-text files like images.
References:
https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files https://docs.python.org/3/library/functions.html#open
if(isset($_POST['form1']))
{
try
{
$user=$_POST['username'];
$pass=$_POST['password'];
$email=$_POST['email'];
$roll=$_POST['roll'];
$class=$_POST['class'];
if(empty($user)) throw new Exception("Name can not empty");
if(empty($pass)) throw new Exception("Password can not empty");
if(empty($email)) throw new Exception("Email can not empty");
if(empty($roll)) throw new Exception("Roll can not empty");
if(empty($class)) throw new Exception("Class can not empty");
$statement=$db->prepare("show table status like 'tbl_std_info'");
$statement->execute();
$result=$statement->fetchAll();
foreach($result as $row)
$new_id=$row[10];
$up_file=$_FILES["image"]["name"];
$file_basename=substr($up_file, 0 , strripos($up_file, "."));
$file_ext=substr($up_file, strripos($up_file, "."));
$f1="$new_id".$file_ext;
if(($file_ext!=".png")&&($file_ext!=".jpg")&&($file_ext!=".jpeg")&&($file_ext!=".gif"))
{
throw new Exception("Only jpg, png, jpeg or gif Logo are allow to upload / Empty Logo Field");
}
move_uploaded_file($_FILES["image"]["tmp_name"],"../std_photo/".$f1);
$statement=$db->prepare("insert into tbl_std_info (username,image,password,email,roll,class) value (?,?,?,?,?,?)");
$statement->execute(array($user,$f1,$pass,$email,$roll,$class));
$success="Registration Successfully Completed";
echo $success;
}
catch(Exception $e)
{
$msg=$e->getMessage();
}
}
It's not possible with CSS3. There is a proposed CSS4 selector, $
, to do just that, which could look like this (Selecting the li
element):
ul $li ul.sub { ... }
See the list of CSS4 Selectors here.
As an alternative, with jQuery, a one-liner you could make use of would be this:
$('ul li:has(ul.sub)').addClass('has_sub');
You could then go ahead and style the li.has_sub
in your CSS.
It should be this:
if (myString!="-1")
{
//Do things
}
Your equals and exclamation are the wrong way round.
I would stick with normal approach to call the file directly, but if you really want to call a function, have a look at JSON-RPC (JSON Remote Procedure Call).
You basically send a JSON string in a specific format to the server, e.g.
{ "method": "echo", "params": ["Hello JSON-RPC"], "id": 1}
which includes the function to call and the parameters of that function.
Of course the server has to know how to handle such requests.
Here is jQuery plugin for JSON-RPC and e.g. the Zend JSON Server as server implementation in PHP.
This might be overkill for a small project or less functions. Easiest way would be karim's answer. On the other hand, JSON-RPC is a standard.
Assuming you have people is List of object
Map<String, String> phoneBook=people.stream()
.collect(toMap(Person::getName, Person::getAddress));
Now you need two steps :
1)
people =removeDuplicate(people);
2)
Map<String, String> phoneBook=people.stream()
.collect(toMap(Person::getName, Person::getAddress));
Here is method to remove duplicate
public static List removeDuplicate(Collection<Person> list) {
if(list ==null || list.isEmpty()){
return null;
}
Object removedDuplicateList =
list.stream()
.distinct()
.collect(Collectors.toList());
return (List) removedDuplicateList;
}
Adding full example here
package com.example.khan.vaquar;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class RemovedDuplicate {
public static void main(String[] args) {
Person vaquar = new Person(1, "Vaquar", "Khan");
Person zidan = new Person(2, "Zidan", "Khan");
Person zerina = new Person(3, "Zerina", "Khan");
// Add some random persons
Collection<Person> duplicateList = Arrays.asList(vaquar, zidan, zerina, vaquar, zidan, vaquar);
//
System.out.println("Before removed duplicate list" + duplicateList);
//
Collection<Person> nonDuplicateList = removeDuplicate(duplicateList);
//
System.out.println("");
System.out.println("After removed duplicate list" + nonDuplicateList);
;
// 1) solution Working code
Map<Object, Object> k = nonDuplicateList.stream().distinct()
.collect(Collectors.toMap(s1 -> s1.getId(), s1 -> s1));
System.out.println("");
System.out.println("Result 1 using method_______________________________________________");
System.out.println("k" + k);
System.out.println("_____________________________________________________________________");
// 2) solution using inline distinct()
Map<Object, Object> k1 = duplicateList.stream().distinct()
.collect(Collectors.toMap(s1 -> s1.getId(), s1 -> s1));
System.out.println("");
System.out.println("Result 2 using inline_______________________________________________");
System.out.println("k1" + k1);
System.out.println("_____________________________________________________________________");
//breacking code
System.out.println("");
System.out.println("Throwing exception _______________________________________________");
Map<Object, Object> k2 = duplicateList.stream()
.collect(Collectors.toMap(s1 -> s1.getId(), s1 -> s1));
System.out.println("");
System.out.println("k2" + k2);
System.out.println("_____________________________________________________________________");
}
public static List removeDuplicate(Collection<Person> list) {
if (list == null || list.isEmpty()) {
return null;
}
Object removedDuplicateList = list.stream().distinct().collect(Collectors.toList());
return (List) removedDuplicateList;
}
}
// Model class
class Person {
public Person(Integer id, String fname, String lname) {
super();
this.id = id;
this.fname = fname;
this.lname = lname;
}
private Integer id;
private String fname;
private String lname;
// Getters and Setters
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getFname() {
return fname;
}
public void setFname(String fname) {
this.fname = fname;
}
public String getLname() {
return lname;
}
public void setLname(String lname) {
this.lname = lname;
}
@Override
public String toString() {
return "Person [id=" + id + ", fname=" + fname + ", lname=" + lname + "]";
}
}
Results :
Before removed duplicate list[Person [id=1, fname=Vaquar, lname=Khan], Person [id=2, fname=Zidan, lname=Khan], Person [id=3, fname=Zerina, lname=Khan], Person [id=1, fname=Vaquar, lname=Khan], Person [id=2, fname=Zidan, lname=Khan], Person [id=1, fname=Vaquar, lname=Khan]]
After removed duplicate list[Person [id=1, fname=Vaquar, lname=Khan], Person [id=2, fname=Zidan, lname=Khan], Person [id=3, fname=Zerina, lname=Khan]]
Result 1 using method_______________________________________________
k{1=Person [id=1, fname=Vaquar, lname=Khan], 2=Person [id=2, fname=Zidan, lname=Khan], 3=Person [id=3, fname=Zerina, lname=Khan]}
_____________________________________________________________________
Result 2 using inline_______________________________________________
k1{1=Person [id=1, fname=Vaquar, lname=Khan], 2=Person [id=2, fname=Zidan, lname=Khan], 3=Person [id=3, fname=Zerina, lname=Khan]}
_____________________________________________________________________
Throwing exception _______________________________________________
Exception in thread "main" java.lang.IllegalStateException: Duplicate key Person [id=1, fname=Vaquar, lname=Khan]
at java.util.stream.Collectors.lambda$throwingMerger$0(Collectors.java:133)
at java.util.HashMap.merge(HashMap.java:1253)
at java.util.stream.Collectors.lambda$toMap$58(Collectors.java:1320)
at java.util.stream.ReduceOps$3ReducingSink.accept(ReduceOps.java:169)
at java.util.Spliterators$ArraySpliterator.forEachRemaining(Spliterators.java:948)
at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708)
at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:499)
at com.example.khan.vaquar.RemovedDuplicate.main(RemovedDuplicate.java:48)
Perhaps it's meaningful to also add that
$('#fieldName').prop('readonly',false);
can be used as a toggle option..
EDIT: chardet seems to be unmantained but most of the answer applies. Check https://pypi.org/project/charset-normalizer/ for an alternative
Correctly detecting the encoding all times is impossible.
(From chardet FAQ:)
However, some encodings are optimized for specific languages, and languages are not random. Some character sequences pop up all the time, while other sequences make no sense. A person fluent in English who opens a newspaper and finds “txzqJv 2!dasd0a QqdKjvz” will instantly recognize that that isn't English (even though it is composed entirely of English letters). By studying lots of “typical” text, a computer algorithm can simulate this kind of fluency and make an educated guess about a text's language.
There is the chardet library that uses that study to try to detect encoding. chardet is a port of the auto-detection code in Mozilla.
You can also use UnicodeDammit. It will try the following methods:
To use Beyond Compare as the difftool for directory diff, remember enable follow symbolic links like so:
In a Folder Compare View → Rules (Referee Icon):
And then, enable follow symbolic links and update session defaults:
OR,
set up the alias like so:
git config --global alias.diffdir "difftool --dir-diff --tool=bc3 --no-prompt --no-symlinks"
Note that in either case, any edits made to the side (left or right) that refers to the current working tree are preserved.
Git doesn't really store history the way you think it does. It calculates history at run-time based on an ancestor chain. If your ancestry is missing blobs, trees, or commits then you may not be able to fully recover your history.
The first thing you can try is to restore the missing items from backup. For example, see if you have a backup of the commit stored as .git/objects/98/4c11abfc9c2839b386f29c574d9e03383fa589
. If so you can restore it.
You may also want to look into git-verify-pack and git-unpack-objects in the event that the commit has already been packed up and you want to return it to a loose object for the purposes of repository surgery.
If you can't replace the missing items from a backup, you may be able to excise the missing history. For example, you might examine your history or reflog to find an ancestor of commit 984c11abfc9c2839b386f29c574d9e03383fa589. If you find one intact, then:
If it works, you will of course lose the intervening history. At this point, if you have a working history log, then it's a good idea to prune your history and reflogs of all unreachable commits and objects.
If your repository is still broken, then hopefully you have an uncorrupted backup or clone you can restore from. If not, but your current working directory contains valid files, then you can always re-initialize Git. For example:
rm -rf .git
git init
git add .
git commit -m 'Re-initialize repository without old history.'
It's drastic, but it may be your only option if your repository history is truly unrecoverable. YMMV.
The article Semicolons in JavaScript are optional makes some really good points about not using semi colons in Javascript. It deals with all the points have been brought up by the answers to this question.
Standard xargs
has no good way to do it; you're better off using find -exec
as someone else suggested, or wrap the sed
in a script which does nothing if there are no arguments. GNU xargs
has the --no-run-if-empty
option, and BSD / OS X xargs
has the -L
option which looks like it should do something similar.
alter table d add constraint pkc_Name primary key (id, code)
should do it. There's lots of options to a basic primary key/index depending on what DB your working with.
Based on @epegzz suggestion for the regex.
( url ) => {
return url.match('^[^?]*')[0].split('/').slice(1)
}
returns an array with paths.
The more current way of this is to update the outDir
property in .angular-cli.json
.
The ng build
command argument --output-path
(or -op
for short) is still supported also, which can be useful if you want multiple values, you can save them in your package.json
as npm scripts.
Beware: The
.angular-cli.json
property is NOT calledoutput-path
like the currently-accepted answer by @cwill747 says. That's theng build
argument only.It's called
outDir
as mentioned above, and it's a under theapps
property.
.
(December 2017)
1-year after adding this answer, someone added a new answer with essentially same information, and the Original Poster changed the accepted answer to the 1-year-late answer containing same information in the first line of this one.
If you want refresh the page you could use like this, but refreshing the page is usually not the best method, it better to try just update the content that you need to be updated.
javascript:
<script language="javascript">
setTimeout(function(){
window.location.reload(1);
}, 30000);
</script>
Very good answer using inheritance, just remember to override the initializer
public class Utf8StringWriter : StringWriter
{
public Utf8StringWriter(StringBuilder sb) : base (sb)
{
}
public override Encoding Encoding { get { return Encoding.UTF8; } }
}
The first argument should be the path to the executable program. So
gdb progname 12271
You can do this from the IPython API.
from IPython.nbformat import current as nbformat
from IPython.nbconvert import PythonExporter
filepath = 'path/to/my_notebook.ipynb'
export_path = 'path/to/my_notebook.py'
with open(filepath) as fh:
nb = nbformat.reads_json(fh.read())
exporter = PythonExporter()
# source is a tuple of python source code
# meta contains metadata
source, meta = exporter.from_notebook_node(nb)
with open(export_path, 'w+') as fh:
fh.writelines(source)
I have used a very simple solution. I have included a HTML element, that calls the method, in my Vue Component that I select, using Vanilla JS, and I trigger click!
In the Vue Component, I have included something like the following:
<span data-id="btnReload" @click="fetchTaskList()"><i class="fa fa-refresh"></i></span>
That I use using Vanilla JS:
const btnReload = document.querySelector('[data-id="btnReload"]');
btnReload.click();
Adding a requestedExecutionLevel
element to your manifest is only half the battle; you have to remember that UAC can be turned off. If it is, you have to perform the check the old school way and put up an error dialog if the user is not administrator
(call IsInRole(WindowsBuiltInRole.Administrator)
on your thread's CurrentPrincipal
).
You are referring to the section "2.3.5 Deploying the demo app" of this "Ruby on Rails Tutorial ":
In section 2.3.1 Planning the application, note that they did:
$ git remote add origin [email protected]:<username>/demo_app.git
$ git push origin master
That is why a simple git push
worked (using here an ssh address).
Did you follow that step and made that first push?
www.github.com/levelone/demo_app
wouldn't be a writable URI for pushing to a GitHub repo.
https://[email protected]/levelone/demo_app.git
should be more appropriate.
Check what git remote -v returns, and if you need to replace the remote address, as described in GitHub help page, use git remote --set-url
.
git remote set-url origin https://[email protected]/levelone/demo_app.git
or
git remote set-url origin [email protected]:levelone/demo_app.git
I was also facing the same problem recently. after struggling a couple of hours,finally a solution came out by addition to
Factory="System.ServiceModel.Activation.WebServiceHostFactory"
to your SVC markup file. e.g.
ServiceHost Language="C#" Debug="true" Service="QuiznetOnline.Web.UI.WebServices.LogService"
Factory="System.ServiceModel.Activation.WebServiceHostFactory"
and now you can compile & run your application successfully.
Initialize the current cursor. Use it to get the position of X and Y
this.Cursor = new Cursor(Cursor.Current.Handle);
int posX = Cursor.Position.X;
int posY = Cursor.Position.Y;
You need to add /// Comment for the member for which warning is displayed.
see below code
public EventLogger()
{
LogFile = string.Format("{0}{1}", LogFilePath, FileName);
}
It displays warning Missing XML comment for publicly visible type or member '.EventLogger()'
I added comment for the member and warning gone.
///<Summary>
/// To write a log <Anycomment as per your code>
///</Summary>
public EventLogger()
{
LogFile = string.Format("{0}{1}", LogFilePath, FileName);
}
if you have a problem on groupActivity dont use this. PARENT is a static from the Parent ActivityGroup.
final AlertDialog.Builder builder = new AlertDialog.Builder(GroupActivityParent.PARENT);
instead of
final AlertDialog.Builder builder = new AlertDialog.Builder(getParent());
In a more general way you can use "INTERVAL". Here some examples:
1) add a day
select sysdate + INTERVAL '1' DAY from dual;
2) add 20 days
select sysdate + INTERVAL '20' DAY from dual;
2) add some minutes
select sysdate + INTERVAL '15' MINUTE from dual;
You can do:
setContentPane(new JLabel(new ImageIcon("resources/taverna.jpg")));
At first line of the Jframe class constructor, that works fine for me
You have to close all of the streams or use try-with-resource block
static public String head(File file) throws FileNotFoundException, UnsupportedEncodingException, IOException
{
final String readLine;
try (FileInputStream fis = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
LineNumberReader lnr = new LineNumberReader(isr))
{
readLine = lnr.readLine();
}
return readLine;
}
Well, base on your code, you would put onkeyup=sum() in each text box txt1 and txt2
Have a look at the helper class: Mage_Customer_Helper_Data
To simply get the customer name, you can write the following code:-
$customerName = Mage::helper('customer')->getCustomerName();
For more information about the customer's entity id, website id, email, etc. you can use getCustomer function. The following code shows what you can get from it:-
echo "<pre>"; print_r(Mage::helper('customer')->getCustomer()->getData()); echo "</pre>";
From the helper class, you can also get information about customer login url, register url, logout url, etc.
From the isLoggedIn function in the helper class, you can also check whether a customer is logged in or not.
FILL_PARENT
is deprecated from the API level 8 and higher and it is renamed for the upper versions as MATCH_PARENT
Both are same FILL_PARENT
and MATCH_PARENT
,FILL_PARENT
was used in the lower version less than API level 8 and MATCH_PATENT are used in higher API level greater than 8.
FILL_PARENT
(renamed MATCH_PARENT
in API Level 8 and higher), which means that the view wants to be as big as its parent (minus padding)
fill_parent
: The view should be as big as its parent (minus padding). This constant is deprecated starting from API Level 8 and is replaced by match_parent
.
For more details please visit this page
(?<!1\.2\.3\.4).*Has exploded
You need to run this with -P to have negative lookbehind (Perl regular expression), so the command is:
grep -P '(?<!1\.2\.3\.4).*Has exploded' test.log
Try this. It uses negative lookbehind to ignore the line if it is preceeded by 1.2.3.4
. Hope that helps!
Here is what worked for me when I deployed to Heroku.
http://flask-cors.readthedocs.org/en/latest/
Install flask-cors by running -
pip install -U flask-cors
from flask import Flask
from flask_cors import CORS, cross_origin
app = Flask(__name__)
cors = CORS(app)
app.config['CORS_HEADERS'] = 'Content-Type'
@app.route("/")
@cross_origin()
def helloWorld():
return "Hello, cross-origin-world!"
I think a most simple solution would be as follows:
(static working: boolean)
in the class where this function exists and every time you call the function, simply make it true whichever you like. Within the function, if the value of working is true, then simply return right away without doing anything. else, perform the task you want. Make sure to change this variable to false once the task is completed i.e. at the end of the line of codes or within the subscribe method when you are done assigning values! This bug is filed here. This is a bug of android devices having API level less than 12. You've to put correct versions of your layouts in drawable-v12 folder which will be used for API level 12 or higher. And an erroneous version(corners switched/reversed) of the same layout will be put in the default drawable folder which will be used by the devices having API level less than 12.
For example: I had to design a button with rounded corner at bottom-right.
In 'drawable' folder - button.xml: I had to make bottom-left corner rounded.
<shape>
<corners android:bottomLeftRadius="15dp"/>
</shape>
In 'drawable-v12' folder - button.xml: Correct version of the layout was placed here to be used for API level 12 or higher.
<shape>
<corners android:bottomLeftRadius="15dp"/>
</shape>
If you are using Python on Ubuntu and you only want it to work on Ubuntu a substantially faster way is the use the terminal's locate
program like this.
import subprocess
def find_files(file_name):
command = ['locate', file_name]
output = subprocess.Popen(command, stdout=subprocess.PIPE).communicate()[0]
output = output.decode()
search_results = output.split('\n')
return search_results
search_results
is a list
of the absolute file paths. This is 10,000's of times faster than the methods above and for one search I've done it was ~72,000 times faster.
If you can modify the HTML: http://jsfiddle.net/8JwhZ/3/
<div class="title">
<span class="name">Cumulative performance</span>
<span class="date">20/02/2011</span>
</div>
.title .date { float:right }
.title .name { float:left }
In your generic method, T
is just a placeholder for a type. However, the compiler doesn't per se know anything about the concrete type(s) being used runtime, so it can't assume that they will have a var
member.
The usual way to circumvent this is to add a generic type constraint to your method declaration to ensure that the types used implement a specific interface (in your case, it could be ITest
):
public void PrintGeneric<T>(T test) where T : ITest
Then, the members of that interface would be directly available inside the method. However, your ITest
is currently empty, you need to declare common stuff there in order to enable its usage within the method.
For anyone else with this issue that arrives here via Google, please check that the host element of the *ngFor
directive is accurate. By this, I mean that I encountered this error and spent a long time researching fixes before realizing that I had put the *ngFor
on an ng-template
element instead of on my component I wanted to repeat.
Incorrect
<ng-template *ngFor=let group of groups$ | async" ...>
<my-component [prop1]="group.key" ... </my-component>
<\ng-template>
Correct
<my-component *ngFor=let group of groups$ | async" [prop1]="group.key" ... </my-component>
I know this is an obvious mistake in hindsight, but I hope an answer here will save someone the headache I now have.
Here is a solution for ES6 where you only want to keep the last item. This solution is functional and Airbnb style compliant.
const things = {
thing: [
{ place: 'here', name: 'stuff' },
{ place: 'there', name: 'morestuff1' },
{ place: 'there', name: 'morestuff2' },
],
};
const removeDuplicates = (array, key) => {
return array.reduce((arr, item) => {
const removed = arr.filter(i => i[key] !== item[key]);
return [...removed, item];
}, []);
};
console.log(removeDuplicates(things.thing, 'place'));
// > [{ place: 'here', name: 'stuff' }, { place: 'there', name: 'morestuff2' }]
A bit of explaining as to what that %2520
is :
The common space character is encoded as %20
as you noted yourself.
The %
character is encoded as %25
.
The way you get %2520
is when your url already has a %20
in it, and gets urlencoded again, which transforms the %20
to %2520
.
Are you (or any framework you might be using) double encoding characters?
Edit:
Expanding a bit on this, especially for LOCAL links. Assuming you want to link to the resource C:\my path\my file.html
:
%
is a valid filename character and as such it will be encoded) when converting to a proper URL (see next point).file://
protocol, you are basically stating that you have taken all precautions and encoded what needs encoding, the rest should be treated as special characters. In the above example, you should thus provide file:///c:/my%20path/my%20file.html
. Aside from fixing slashes, clients should not encode characters here.NOTES:
/
are used in URLs, reverse slashes \
in Windows paths, but most clients will work with both by converting them to the proper forward slash. file://localhost/c:/my%20path/my%file.html
), but again most clients will work without the host part (ie two slashes only) by assuming you mean the local machine and adding the third slash.I do a fair amount of vibration analysis and look at large data sets (tens and hundreds of millions of points). My testing showed the pandas.read_csv() function to be 20 times faster than numpy.genfromtxt(). And the genfromtxt() function is 3 times faster than the numpy.loadtxt(). It seems that you need pandas for large data sets.
I posted the code and data sets I used in this testing on a blog discussing MATLAB vs Python for vibration analysis.
If your dateString is RFC282 and ISO8601 compliant:
pass your string into the Date Constructor:
const dateString = "2020-10-30T12:52:27+05:30"; // ISO8601 compliant dateString
const D = new Date(dateString); // {object Date}
from here you can extract the desired values by using Date Getters:
D.getMonth() + 1 // 10 (PS: +1 since Month is 0-based)
D.getDate() // 30
D.getFullYear() // 2020
If you use a non standard date string:
destructure the string into known parts, and than pass the variables to the Date Constructor:
new Date(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]])
const dateString = "30/10/2020 12:52:27";
const [d, M, y, h, m, s] = dateString.match(/\d+/g);
// PS: M-1 since Month is 0-based
const D = new Date(y, M-1, d, h, m, s); // {object Date}
D.getMonth() + 1 // 10 (PS: +1 since Month is 0-based)
D.getDate() // 30
D.getFullYear() // 2020
I found the easiest way to locate it, you can use
which python
it will show something like this:
/usr/bin/python
Regarding to Peter's answer and Micheal's addition to it you may find How Do I Automatically Generate A .jar File In An Eclipse Java Project useful. Because even you have "*.jardesc" file on your project you have to run it manually. It may cools down your "eclipse click hassle" a bit.
There is a good, simple example of exactly this, here: http://www.queness.com/post/77/simple-jquery-modal-window-tutorial
What I ended up doing is create a new KeyContainer name based off of the current DateTime (DateTime.Now.Ticks.ToString()) whenever I need to create a new key and save the container name and public key to the database. Also, whenever I create a new key I would do the following:
public static string ConvertToNewKey(string oldPrivateKey)
{
// get the current container name from the database...
rsa.PersistKeyInCsp = false;
rsa.Clear();
rsa = null;
string privateKey = AssignNewKey(true); // create the new public key and container name and write them to the database...
// re-encrypt existing data to use the new keys and write to database...
return privateKey;
}
public static string AssignNewKey(bool ReturnPrivateKey){
string containerName = DateTime.Now.Ticks.ToString();
// create the new key...
// saves container name and public key to database...
// and returns Private Key XML.
}
before creating the new key.
python 3 https://docs.python.org/3.5/howto/sorting.html#the-old-way-using-the-cmp-parameter
from functools import cmp_to_key
def custom_compare(x, y):
# custom comparsion of x[0], x[1] with y[0], y[1]
return 0
sorted(entries, key=lambda e: (cmp_to_key(custom_compare)(e[0]), e[1]))
To get exact name of control, use:
string controlName = Page.FindControl(Page.Request.Params["__EVENTTARGET"]).ID;
Looks like you have a typo -- "trustStrore" should be "trustStore", i.e.
System.setProperty("javax.net.ssl.trustStrore", "cacerts.jks");
should be:
System.setProperty("javax.net.ssl.trustStore", "cacerts.jks");
In 2020, you can use css snap, but before Chrome 81 the layout change will not trigger re-snap, a pure css chat ui works on Chrome 81, also you can check Can I use CSS snap.
This demo will snap the last element if visible, scroll to bottom to see the effect.
.container {
overflow-y: scroll;
overscroll-behavior-y: contain;
scroll-snap-type: y proximity;
}
.container > div > div:last-child {
scroll-snap-align: end;
}
.container > div > div {
background: lightgray;
height: 3rem;
font-size: 1.5rem;
}
.container > div > div:nth-child(2n) {
background: gray;
}
_x000D_
<div class="container" style="height:6rem">
<div>
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
</div>
</div>
_x000D_
EDIT
use scroll-snap-type: y proximity;
, scroll up easier.
If an Immutable/Singleton collections refers to the one which having only one object and which is not further gets modified, then the same functionality can be achieved by making a collection "UnmodifiableCollection" having only one object. Since the same functionality can be achieved by Unmodifiable Collection with one object, then what special purpose the Singleton Collection serves for?
event.preventDefault()
Doesn't work in all browsers. Instead you could return false in OnClick event.
onClick="toggle_it('tr1');toggle_it('tr2'); return false;">
Not sure if this is the best way, but I tested in IE, FF and Chrome and its working fine.
Follow this:
Create a bin
folder in any directory(to be used in step 3).
Download winutils.exe and place it in the bin directory.
Now add System.setProperty("hadoop.home.dir", "PATH/TO/THE/DIR");
in your code.
SELECT * FROM TABLE WHERE ID = (SELECT MAX(ID) FROM TABLE)
1. From Package Explorer
open the Filters...
dialog:
2. Then uncheck .* resources
option:
Both other answers are correct, but I thought it worth noting that the place where I got stuck was not realizing that you'll need order by the alias and make sure that the alias is the same for both the selects... so
select 'foo'
union
select item as `foo`
from myTable
order by `foo`
notice that I'm using single quotes in the first select but backticks for the others.
That will get you the sorting you need.
This is what worked for me:
Call it in your viewDidAppear: method.
- (void) viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
[UIViewController attemptRotationToDeviceOrientation];
}
editTxt.setOnFocusChangeListener { v, hasFocus ->
val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
if (hasFocus) {
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY)
} else {
imm.hideSoftInputFromWindow(v.windowToken, 0)
}
}
this issue comes up with 2 reasons
1) the android SDK has not been install 2) the build toold version corresponsind to the android SDK is not installed
to start
open terminal and type android
and install API 26(updated one) and build tools version 26.0.1 or 26.0.2
then try to run using command ionic cordova build android
Angular itself doesn't provide if/else functionality, but you can get it by including this module:
https://github.com/zachsnow/ng-elif
In its own words, it's just "a simple collection of control flow directives: ng-if, ng-else-if, and ng-else." It's easy and intuitive to use.
Example:
<div ng-if="someCondition">
...
</div>
<div ng-else-if="someOtherCondition">
...
</div>
<div ng-else>
...
</div>
I'm late to the party, but this solution worked for me quite well. Based on this library, you can use a function lik this - setting the image, quality, max-width, and output format (jepg,png):
function compress(source_img_obj, quality, maxWidth, output_format){
var mime_type = "image/jpeg";
if(typeof output_format !== "undefined" && output_format=="png"){
mime_type = "image/png";
}
maxWidth = maxWidth || 1000;
var natW = source_img_obj.naturalWidth;
var natH = source_img_obj.naturalHeight;
var ratio = natH / natW;
if (natW > maxWidth) {
natW = maxWidth;
natH = ratio * maxWidth;
}
var cvs = document.createElement('canvas');
cvs.width = natW;
cvs.height = natH;
var ctx = cvs.getContext("2d").drawImage(source_img_obj, 0, 0, natW, natH);
var newImageData = cvs.toDataURL(mime_type, quality/100);
var result_image_obj = new Image();
result_image_obj.src = newImageData;
return result_image_obj;
}
Console.WriteLine(Path.GetDirectoryName(@"C:\hello\my\dear\world.hm"));
Another way ( longer ) In VB.net [ Say 2300 Start and 0700 Finish next day ]
If tsStart > tsFinish Then
' Take Hours difference and adjust accordingly
tsDifference = New TimeSpan((24 - tsStart.Hours) + tsFinish.Hours, 0, 0)
' Add Minutes to Difference
tsDifference = tsDifference.Add(New TimeSpan(0, Math.Abs(tsStart.Minutes - tsFinish.Minutes), 0))
' Add Seonds to Difference
tsDifference = tsDifference.Add(New TimeSpan(0, 0, Math.Abs(tsStart.Seconds - tsFinish.Seconds)))
The standard C++ solution presented here by litb will not work as expected if the method happens to be defined in a base class.
For a solution that handles this situation refer to :
In Russian : http://www.rsdn.ru/forum/message/2759773.1.aspx
English Translation by Roman.Perepelitsa : http://groups.google.com/group/comp.lang.c++.moderated/tree/browse_frm/thread/4f7c7a96f9afbe44/c95a7b4c645e449f?pli=1
It is insanely clever. However one issue with this solutiion is that gives compiler errors if the type being tested is one that cannot be used as a base class (e.g. primitive types)
In Visual Studio, I noticed that if working with method having no arguments, an extra pair of redundant ( ) needs to be inserted around the argments to deduce( ) in the sizeof expression.
Open SQL Management Studio Express and log in to the server to which you want to attach the database. In the 'Object Explorer' window, right-click on the 'Databases' folder and select 'Attach...' The 'Attach Databases' window will open; inside that window click 'Add...' and then navigate to your .MDF file and click 'OK'. Click 'OK' once more to finish attaching the database and you are done. The database should be available for use. best regards :)
This work for me!
$(document).ready(function() {
$(document).on("click", "#tableId tbody tr", function() {
//some think
});
});
$(window).bind("load", function() {
// write your code here
});
Use a DecimalFormat object with a format string of "0.#".
To see the public tables you can do
list tables
\dt
list table, view, and access privileges
\dp or \z
or just the table names
select table_name from information_schema.tables where table_schema = 'public';
Here is a great resource from Microsoft which includes a high level features overview for each .NET release since 1.0 up to the present day. It also include information about the associated Visual Studio release and Windows version compatibility.
If the purpose is to obtain a bitmap, this is very simple:
Canvas canvas = new Canvas();
canvas.setBitmap(image);
canvas.drawBitmap(image2, new Matrix(), null);
In the end, image will contain the overlap of image and image2.
I solved the problem easily (pragmatic) by adding the option to the constructor. Thus, i use that only when needed.
public class Something : DbContext
{
public Something(bool MultipleActiveResultSets = false)
{
this.Database
.Connection
.ConnectionString = Shared.ConnectionString /* your connection string */
+ (MultipleActiveResultSets ? ";MultipleActiveResultSets=true;" : "");
}
...
thanks for this post. I want to add something that can be useful.
For IE, it is good to use
object["property"] = value;
syntax because some special words in IE can give you an error.
An example:
object.class = 'value';
this fails in IE, because "class" is a special word. I spent several hours with this.
Just a small side-note... If you are using this with other scripts, the $ on the last line will cause a conflict. Just replace it with jQuery and you're good.
jQuery(function(){
jQuery('#showall').click(function(){
jQuery('.targetDiv').show();
});
jQuery('.showSingle').click(function(){
jQuery('.targetDiv').hide();
jQuery('#div'+jQuery(this).attr('target')).show();
});
});
For me its a permissions issue:
On the git server run this command on the repo directory
sudo chmod -R 777 theDirectory/
It is to my understanding that you want to embed a video on your site that:
This Demo Here does just that. You have to place another embed class outside of the object/embed/iframe tag as per the the instructions here - but you're also able to use a video tag instead of the object tag even though it's not specified.
<div align="center" class="embed-responsive embed-responsive-16by9">
<video autoplay loop class="embed-responsive-item">
<source src="http://techslides.com/demos/sample-videos/small.mp4" type="video/mp4">
</video>
</div>
You can use the stringr
library:
library('stringr')
a <- runif(10)
b <- letters[1:10]
c <- c(rep('A-B', 4), rep('A_B', 6))
data <- data.frame(a, b, c)
data
# a b c
# 1 0.19426707 a A-B
# 2 0.12902673 b A-B
# 3 0.78324955 c A-B
# 4 0.06469028 d A-B
# 5 0.34752264 e A_C
# 6 0.55313288 f A_C
# 7 0.31264280 g A_C
# 8 0.33759921 h A_C
# 9 0.72322599 i A_C
# 10 0.25223075 j A_C
data$c <- str_replace_all(data$c, '_', '-')
data
# a b c
# 1 0.19426707 a A-B
# 2 0.12902673 b A-B
# 3 0.78324955 c A-B
# 4 0.06469028 d A-B
# 5 0.34752264 e A-C
# 6 0.55313288 f A-C
# 7 0.31264280 g A-C
# 8 0.33759921 h A-C
# 9 0.72322599 i A-C
# 10 0.25223075 j A-C
Note that this does change factored variables into character.
The posted solutions will not link any hidden files. To include them, try this:
cd /usr/lib
find /mnt/usr/lib -maxdepth 1 -print "%P\n" | while read file; do ln -s "/mnt/usr/lib/$file" "$file"; done
If you should happen to want to recursively create the directories and only link files (so that if you create a file within a directory, it really is in /usr/lib
not /mnt/usr/lib
), you could do this:
cd /usr/lib
find /mnt/usr/lib -mindepth 1 -depth -type d -printf "%P\n" | while read dir; do mkdir -p "$dir"; done
find /mnt/usr/lib -type f -printf "%P\n" | while read file; do ln -s "/mnt/usr/lib/$file" "$file"; done
I actually happened to have suffered from the same problem, but none of the provided answers are 100% working with debian:latest, even if they provide good hints.
The biggest difference is that you should make sure both locales and locales-all are installed, the latter already containing en_US.UTF-8, so you don't have to generate it with local-gen or dpkg-reconfigure.
Here's what I've done in my Dockerfile to make it work:
FROM debian:latest
RUN apt-get update
RUN apt-get install -y locales locales-all
ENV LC_ALL en_US.UTF-8
ENV LANG en_US.UTF-8
ENV LANGUAGE en_US.UTF-8
Difference between PUT, POST, GET, DELETE and PATCH IN HTTP Verbs:
The most commonly used HTTP verbs POST, GET, PUT, DELETE are similar to CRUD (Create, Read, Update and Delete) operations in database. We specify these HTTP verbs in the capital case. So, the below is the comparison between them.
PATCH: Submits a partial modification to a resource. If you only need to update one field for the resource, you may want to use the PATCH method.
Note:
Since POST, PUT, DELETE modifies the content, the tests with Fiddler for the below url just mimicks the updations. It doesn't delete or modify actually. We can just see the status codes to check whether insertions, updations, deletions occur.
URL: http://jsonplaceholder.typicode.com/posts/
1) GET:
GET is the simplest type of HTTP request method; the one that browsers use each time you click a link or type a URL into the address bar. It instructs the server to transmit the data identified by the URL to the client. Data should never be modified on the server side as a result of a GET request. In this sense, a GET request is read-only.
Checking with Fiddler or PostMan: We can use Fiddler for checking the response. Open Fiddler and select the Compose tab. Specify the verb and url as shown below and click Execute to check the response.
Verb: GET
url: http://jsonplaceholder.typicode.com/posts/
Response: You will get the response as:
"userId": 1, "id": 1, "title": "sunt aut...", "body": "quia et suscipit..."
In the “happy” (or non-error) path, GET returns a representation in XML or JSON and an HTTP response code of 200 (OK). In an error case, it most often returns a 404 (NOT FOUND) or 400 (BAD REQUEST).
2) POST:
The POST verb is mostly utilized to create new resources. In particular, it's used to create subordinate resources. That is, subordinate to some other (e.g. parent) resource.
On successful creation, return HTTP status 201, returning a Location header with a link to the newly-created resource with the 201 HTTP status.
Checking with Fiddler or PostMan: We can use Fiddler for checking the response. Open Fiddler and select the Compose tab. Specify the verb and url as shown below and click Execute to check the response.
Verb: POST
url: http://jsonplaceholder.typicode.com/posts/
Request Body:
data: { title: 'foo', body: 'bar', userId: 1000, Id : 1000 }
Response: You would receive the response code as 201.
If we want to check the inserted record with Id = 1000 change the verb to Get and use the same url and click Execute.
As said earlier, the above url only allows reads (GET), we cannot read the updated data in real.
3) PUT:
PUT is most-often utilized for update capabilities, PUT-ing to a known resource URI with the request body containing the newly-updated representation of the original resource.
Checking with Fiddler or PostMan: We can use Fiddler for checking the response. Open Fiddler and select the Compose tab. Specify the verb and url as shown below and click Execute to check the response.
Verb: PUT
url: http://jsonplaceholder.typicode.com/posts/1
Request Body:
data: { title: 'foo', body: 'bar', userId: 1, Id : 1 }
Response: On successful update it returns 200 (or 204 if not returning any content in the body) from a PUT.
4) DELETE:
DELETE is pretty easy to understand. It is used to delete a resource identified by a URI.
On successful deletion, return HTTP status 200 (OK) along with a response body, perhaps the representation of the deleted item (often demands too much bandwidth), or a wrapped response (see Return Values below). Either that or return HTTP status 204 (NO CONTENT) with no response body. In other words, a 204 status with no body, or the JSEND-style response and HTTP status 200 are the recommended responses.
Checking with Fiddler or PostMan: We can use Fiddler for checking the response. Open Fiddler and select the Compose tab. Specify the verb and url as shown below and click Execute to check the response.
Verb: DELETE
url: http://jsonplaceholder.typicode.com/posts/1
Response: On successful deletion it returns HTTP status 200 (OK) along with a response body.
Example between PUT and PATCH
PUT
If I had to change my firstname then send PUT request for Update:
{ "first": "Nazmul", "last": "hasan" } So, here in order to update the first name we need to send all the parameters of the data again.
PATCH:
Patch request says that we would only send the data that we need to modify without modifying or effecting other parts of the data. Ex: if we need to update only the first name, we pass only the first name.
Please refer the below links for more information:
https://jsonplaceholder.typicode.com/
https://github.com/typicode/jsonplaceholder#how-to
SELECT CONVERT(CHAR(10),GETDATE(),103) + ' ' + RIGHT(CONVERT(CHAR(26),GETDATE(),109),14)
In your Main method, you're trying to access, for instance, club
(which is protected), when you should be accessing myclub
which is the public property that you created.
Not LAMP but if you use C# this is the code I use:
Code originally from:
https://github.com/kspearrin/Otp.NET
The Base32Encoding class is from this answer:
https://stackoverflow.com/a/7135008/3850405
Example program:
class Program
{
static void Main(string[] args)
{
var bytes = Base32Encoding.ToBytes("JBSWY3DPEHPK3PXP");
var totp = new Totp(bytes);
var result = totp.ComputeTotp();
var remainingTime = totp.RemainingSeconds();
}
}
Totp:
public class Totp
{
const long unixEpochTicks = 621355968000000000L;
const long ticksToSeconds = 10000000L;
private const int step = 30;
private const int totpSize = 6;
private byte[] key;
public Totp(byte[] secretKey)
{
key = secretKey;
}
public string ComputeTotp()
{
var window = CalculateTimeStepFromTimestamp(DateTime.UtcNow);
var data = GetBigEndianBytes(window);
var hmac = new HMACSHA1();
hmac.Key = key;
var hmacComputedHash = hmac.ComputeHash(data);
int offset = hmacComputedHash[hmacComputedHash.Length - 1] & 0x0F;
var otp = (hmacComputedHash[offset] & 0x7f) << 24
| (hmacComputedHash[offset + 1] & 0xff) << 16
| (hmacComputedHash[offset + 2] & 0xff) << 8
| (hmacComputedHash[offset + 3] & 0xff) % 1000000;
var result = Digits(otp, totpSize);
return result;
}
public int RemainingSeconds()
{
return step - (int)(((DateTime.UtcNow.Ticks - unixEpochTicks) / ticksToSeconds) % step);
}
private byte[] GetBigEndianBytes(long input)
{
// Since .net uses little endian numbers, we need to reverse the byte order to get big endian.
var data = BitConverter.GetBytes(input);
Array.Reverse(data);
return data;
}
private long CalculateTimeStepFromTimestamp(DateTime timestamp)
{
var unixTimestamp = (timestamp.Ticks - unixEpochTicks) / ticksToSeconds;
var window = unixTimestamp / (long)step;
return window;
}
private string Digits(long input, int digitCount)
{
var truncatedValue = ((int)input % (int)Math.Pow(10, digitCount));
return truncatedValue.ToString().PadLeft(digitCount, '0');
}
}
Base32Encoding:
public static class Base32Encoding
{
public static byte[] ToBytes(string input)
{
if (string.IsNullOrEmpty(input))
{
throw new ArgumentNullException("input");
}
input = input.TrimEnd('='); //remove padding characters
int byteCount = input.Length * 5 / 8; //this must be TRUNCATED
byte[] returnArray = new byte[byteCount];
byte curByte = 0, bitsRemaining = 8;
int mask = 0, arrayIndex = 0;
foreach (char c in input)
{
int cValue = CharToValue(c);
if (bitsRemaining > 5)
{
mask = cValue << (bitsRemaining - 5);
curByte = (byte)(curByte | mask);
bitsRemaining -= 5;
}
else
{
mask = cValue >> (5 - bitsRemaining);
curByte = (byte)(curByte | mask);
returnArray[arrayIndex++] = curByte;
curByte = (byte)(cValue << (3 + bitsRemaining));
bitsRemaining += 3;
}
}
//if we didn't end with a full byte
if (arrayIndex != byteCount)
{
returnArray[arrayIndex] = curByte;
}
return returnArray;
}
public static string ToString(byte[] input)
{
if (input == null || input.Length == 0)
{
throw new ArgumentNullException("input");
}
int charCount = (int)Math.Ceiling(input.Length / 5d) * 8;
char[] returnArray = new char[charCount];
byte nextChar = 0, bitsRemaining = 5;
int arrayIndex = 0;
foreach (byte b in input)
{
nextChar = (byte)(nextChar | (b >> (8 - bitsRemaining)));
returnArray[arrayIndex++] = ValueToChar(nextChar);
if (bitsRemaining < 4)
{
nextChar = (byte)((b >> (3 - bitsRemaining)) & 31);
returnArray[arrayIndex++] = ValueToChar(nextChar);
bitsRemaining += 5;
}
bitsRemaining -= 3;
nextChar = (byte)((b << bitsRemaining) & 31);
}
//if we didn't end with a full char
if (arrayIndex != charCount)
{
returnArray[arrayIndex++] = ValueToChar(nextChar);
while (arrayIndex != charCount) returnArray[arrayIndex++] = '='; //padding
}
return new string(returnArray);
}
private static int CharToValue(char c)
{
int value = (int)c;
//65-90 == uppercase letters
if (value < 91 && value > 64)
{
return value - 65;
}
//50-55 == numbers 2-7
if (value < 56 && value > 49)
{
return value - 24;
}
//97-122 == lowercase letters
if (value < 123 && value > 96)
{
return value - 97;
}
throw new ArgumentException("Character is not a Base32 character.", "c");
}
private static char ValueToChar(byte b)
{
if (b < 26)
{
return (char)(b + 65);
}
if (b < 32)
{
return (char)(b + 24);
}
throw new ArgumentException("Byte is not a value Base32 value.", "b");
}
}
You need to put the JavaScript at the end of the body tag.
It doesn't find it because it's not in the DOM yet!
You can also wrap it in the onload event handler like this:
window.onload = function() {
var refButton = document.getElementById( 'btnButton' );
refButton.onclick = function() {
alert( 'I am clicked!' );
}
}
visit this link for reference:http://codepen.io/kalaiselvan/pen/RRBzda
<script>
var app=angular.module('formvalid', ['ui.bootstrap','ui.utils']);
app.controller('validationCtrl',function($scope){
$scope.data=[
[
"Tiger Nixon",
"System Architect",
"Edinburgh",
"5421",
"2011\/04\/25",
"$320,800"
],
[
"Garrett Winters",
"Accountant",
"Tokyo",
"8422",
"2011\/07\/25",
"$170,750"
],
[
"Ashton Cox",
"Junior Technical Author",
"San Francisco",
"1562",
"2009\/01\/12",
"$86,000"
],
[
"Cedric Kelly",
"Senior Javascript Developer",
"Edinburgh",
"6224",
"2012\/03\/29",
"$433,060"
],
[
"Airi Satou",
"Accountant",
"Tokyo",
"5407",
"2008\/11\/28",
"$162,700"
],
[
"Brielle Williamson",
"Integration Specialist",
"New York",
"4804",
"2012\/12\/02",
"$372,000"
],
[
"Herrod Chandler",
"Sales Assistant",
"San Francisco",
"9608",
"2012\/08\/06",
"$137,500"
],
[
"Rhona Davidson",
"Integration Specialist",
"Tokyo",
"6200",
"2010\/10\/14",
"$327,900"
],
[
"Colleen Hurst",
"Javascript Developer",
"San Francisco",
"2360",
"2009\/09\/15",
"$205,500"
],
[
"Sonya Frost",
"Software Engineer",
"Edinburgh",
"1667",
"2008\/12\/13",
"$103,600"
],
[
"Jena Gaines",
"Office Manager",
"London",
"3814",
"2008\/12\/19",
"$90,560"
],
[
"Quinn Flynn",
"Support Lead",
"Edinburgh",
"9497",
"2013\/03\/03",
"$342,000"
],
[
"Charde Marshall",
"Regional Director",
"San Francisco",
"6741",
"2008\/10\/16",
"$470,600"
],
[
"Haley Kennedy",
"Senior Marketing Designer",
"London",
"3597",
"2012\/12\/18",
"$313,500"
],
[
"Tatyana Fitzpatrick",
"Regional Director",
"London",
"1965",
"2010\/03\/17",
"$385,750"
],
[
"Michael Silva",
"Marketing Designer",
"London",
"1581",
"2012\/11\/27",
"$198,500"
],
[
"Paul Byrd",
"Chief Financial Officer (CFO)",
"New York",
"3059",
"2010\/06\/09",
"$725,000"
],
[
"Gloria Little",
"Systems Administrator",
"New York",
"1721",
"2009\/04\/10",
"$237,500"
],
[
"Bradley Greer",
"Software Engineer",
"London",
"2558",
"2012\/10\/13",
"$132,000"
],
[
"Dai Rios",
"Personnel Lead",
"Edinburgh",
"2290",
"2012\/09\/26",
"$217,500"
],
[
"Jenette Caldwell",
"Development Lead",
"New York",
"1937",
"2011\/09\/03",
"$345,000"
],
[
"Yuri Berry",
"Chief Marketing Officer (CMO)",
"New York",
"6154",
"2009\/06\/25",
"$675,000"
],
[
"Caesar Vance",
"Pre-Sales Support",
"New York",
"8330",
"2011\/12\/12",
"$106,450"
],
[
"Doris Wilder",
"Sales Assistant",
"Sidney",
"3023",
"2010\/09\/20",
"$85,600"
],
[
"Angelica Ramos",
"Chief Executive Officer (CEO)",
"London",
"5797",
"2009\/10\/09",
"$1,200,000"
],
[
"Gavin Joyce",
"Developer",
"Edinburgh",
"8822",
"2010\/12\/22",
"$92,575"
],
[
"Jennifer Chang",
"Regional Director",
"Singapore",
"9239",
"2010\/11\/14",
"$357,650"
],
[
"Brenden Wagner",
"Software Engineer",
"San Francisco",
"1314",
"2011\/06\/07",
"$206,850"
],
[
"Fiona Green",
"Chief Operating Officer (COO)",
"San Francisco",
"2947",
"2010\/03\/11",
"$850,000"
],
[
"Shou Itou",
"Regional Marketing",
"Tokyo",
"8899",
"2011\/08\/14",
"$163,000"
],
[
"Michelle House",
"Integration Specialist",
"Sidney",
"2769",
"2011\/06\/02",
"$95,400"
],
[
"Suki Burks",
"Developer",
"London",
"6832",
"2009\/10\/22",
"$114,500"
],
[
"Prescott Bartlett",
"Technical Author",
"London",
"3606",
"2011\/05\/07",
"$145,000"
],
[
"Gavin Cortez",
"Team Leader",
"San Francisco",
"2860",
"2008\/10\/26",
"$235,500"
],
[
"Martena Mccray",
"Post-Sales support",
"Edinburgh",
"8240",
"2011\/03\/09",
"$324,050"
],
[
"Unity Butler",
"Marketing Designer",
"San Francisco",
"5384",
"2009\/12\/09",
"$85,675"
],
[
"Howard Hatfield",
"Office Manager",
"San Francisco",
"7031",
"2008\/12\/16",
"$164,500"
],
[
"Hope Fuentes",
"Secretary",
"San Francisco",
"6318",
"2010\/02\/12",
"$109,850"
],
[
"Vivian Harrell",
"Financial Controller",
"San Francisco",
"9422",
"2009\/02\/14",
"$452,500"
],
[
"Timothy Mooney",
"Office Manager",
"London",
"7580",
"2008\/12\/11",
"$136,200"
],
[
"Jackson Bradshaw",
"Director",
"New York",
"1042",
"2008\/09\/26",
"$645,750"
],
[
"Olivia Liang",
"Support Engineer",
"Singapore",
"2120",
"2011\/02\/03",
"$234,500"
],
[
"Bruno Nash",
"Software Engineer",
"London",
"6222",
"2011\/05\/03",
"$163,500"
],
[
"Sakura Yamamoto",
"Support Engineer",
"Tokyo",
"9383",
"2009\/08\/19",
"$139,575"
],
[
"Thor Walton",
"Developer",
"New York",
"8327",
"2013\/08\/11",
"$98,540"
],
[
"Finn Camacho",
"Support Engineer",
"San Francisco",
"2927",
"2009\/07\/07",
"$87,500"
],
[
"Serge Baldwin",
"Data Coordinator",
"Singapore",
"8352",
"2012\/04\/09",
"$138,575"
],
[
"Zenaida Frank",
"Software Engineer",
"New York",
"7439",
"2010\/01\/04",
"$125,250"
],
[
"Zorita Serrano",
"Software Engineer",
"San Francisco",
"4389",
"2012\/06\/01",
"$115,000"
],
[
"Jennifer Acosta",
"Junior Javascript Developer",
"Edinburgh",
"3431",
"2013\/02\/01",
"$75,650"
],
[
"Cara Stevens",
"Sales Assistant",
"New York",
"3990",
"2011\/12\/06",
"$145,600"
],
[
"Hermione Butler",
"Regional Director",
"London",
"1016",
"2011\/03\/21",
"$356,250"
],
[
"Lael Greer",
"Systems Administrator",
"London",
"6733",
"2009\/02\/27",
"$103,500"
],
[
"Jonas Alexander",
"Developer",
"San Francisco",
"8196",
"2010\/07\/14",
"$86,500"
],
[
"Shad Decker",
"Regional Director",
"Edinburgh",
"6373",
"2008\/11\/13",
"$183,000"
],
[
"Michael Bruce",
"Javascript Developer",
"Singapore",
"5384",
"2011\/06\/27",
"$183,000"
],
[
"Donna Snider",
"Customer Support",
"New York",
"4226",
"2011\/01\/25",
"$112,000"
]
]
$scope.dataTableOpt = {
//if any ajax call
};
});
</script>
<div class="container" ng-app="formvalid">
<div class="panel" data-ng-controller="validationCtrl">
<div class="panel-heading border">
<h2>Data table using jquery datatable in Angularjs </h2>
</div>
<div class="panel-body">
<table class="table table-bordered bordered table-striped table-condensed datatable" ui-jq="dataTable" ui-options="dataTableOpt">
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Start Date</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="n in data">
<td>{{$index+1}}</td>
<td>{{n[0]}}</td>
<td>{{n[1]}}</td>
<td>{{n[2]}}</td>
<td>{{n[3]}}</td>
<td>{{n[4] | date:'dd/MM/yyyy'}}</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
Why not use
$appended = array_merge($a,$b);
Why don't you want to use this, the correct, built-in method.
Image can not be shown until it serves from any server. so you need to upload the image to your server to show its preview.
use this for horizontal divider
<View
android:layout_width="1dp"
android:layout_height="match_parent"
android:background="@color/honeycombish_blue" />
and this for vertical divider
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="@color/honeycombish_blue" />
OR if you can use the LinearLayout divider, for horizontal divider
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<size android:height="1dp"/>
<solid android:color="#f6f6f6"/>
</shape>
and in LinearLayout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="@drawable/divider"
android:orientation="vertical"
android:showDividers="middle" >
If you want to user vertical divider then in place of android:height="1dp"
in shape use android:width="1dp"
Tip: Don't forget the android:showDividers
item.
When you say "a matrix of random numbers", you can use numpy as Pavel https://stackoverflow.com/a/15451997/6169225 mentioned above, in this case I'm assuming to you it is irrelevant what distribution these (pseudo) random numbers adhere to.
However, if you require a particular distribution (I imagine you are interested in the uniform distribution), numpy.random
has very useful methods for you. For example, let's say you want a 3x2 matrix with a pseudo random uniform distribution bounded by [low,high]. You can do this like so:
numpy.random.uniform(low,high,(3,2))
Note, you can replace uniform
by any number of distributions supported by this library.
Further reading: https://docs.scipy.org/doc/numpy/reference/routines.random.html
Check out your TNS Names, this must not have spaces at the left side of the ALIAS
Best regards
One indirect solution can be to use std::deque instead. It supports all operations of queue and you can iterate over it just by using for(auto& x:qu)
. It's much more efficient than using a temporary copy of queue for iteration.
This works for me:
ListBox x = new ListBox();
x.Items.Add(new ListItem("Hello", "1"));
x.Items.Add(new ListItem("Bye", "2"));
Console.Write(x.Items[0].Value);
Sean it works fine i've just used this code
$content = preg_replace("/<img[^>]+\>/i", " ", $content);
echo $content;
//the result it's only the plain text. It works!!!
I also got the same running java JDBC in NetBeans. This is how it fixed
I use Xampp. In conf button of Apache I opened httpd.conf file and on first line I typed
# Set timezone to Europe/Athens UTC+02:00
SetEnv TZ Europe/Athens.
In conf button of MySQL I opened my.ini file and on last line I typed "Europe/Athens"
Stopped and started both Apache and MySQL
Problem fixed.
*(Local mechine time zone is different, but no problem.)
I just encountered the same problem myself.
... = reader["myYear"] as int?;
works and is clean.
It works with any type without an issue. If the result is DBNull, it returns null as the conversion fails.
I am using this, which works for me.
cell?.selectionStyle = UITableViewCellSelectionStyle.None
Instead of using position:relative
in #icons
, you could just take that away and maybe add a z-index or something so the picture won't get covered up. Hope this helps.
In addition to this answer, note that in Node.js if you access JSON with the array syntax []
all nested JSON keys should follow that syntax
This is the wrong way
json.first.second.third['comment']
and will will give you the 'undefined' error.
This is the correct way
json['first']['second']['third']['comment']
@anothershrubery answer worked for me. I've made an enhancement using StringEntensions Class so I can easily convert any string at all in my program.
Method:
public static class StringExtensions
{
public static string ToUTF8(this string text)
{
return Encoding.UTF8.GetString(Encoding.Default.GetBytes(text));
}
}
Usage:
string myString = "Acción";
string strConverted = myString.ToUTF8();
Or simply:
string strConverted = "Acción".ToUTF8();
Is it possible to have multiple version of tensorflow on the same OS?
Yes, you can use python virtual environments for this. From the docs:
A Virtual Environment is a tool to keep the dependencies required by different projects in separate places, by creating virtual Python environments for them. It solves the “Project X depends on version 1.x but, Project Y needs 4.x” dilemma, and keeps your global site-packages directory clean and manageable.
After you have install virtualenv (see the docs), you can create a virtual environment for the tutorial and install the tensorflow version you need in it:
PATH_TO_PYTHON=/usr/bin/python3.5
virtualenv -p $PATH_TO_PYTHON my_tutorial_env
source my_tutorial_env/bin/activate # this activates your new environment
pip install tensorflow==1.1
PATH_TO_PYTHON
should point to where python is installed on your system.
When you want to use the other version of tensorflow execute:
deactivate my_tutorial_env
Now you can work again with the tensorflow version that was already installed on your system.
You can use flexbox for this.
ul {
display: flex;
align-items: center;
}
A detailed explanation of how to use flexbox can be found here.
You must make a new array, use System.arraycopy
to copy the prefix and suffix, and set that one slot to the new value.
This is what I did.
$('.selectpicker').on('changed.bs.select', function (e, clickedIndex, newValue, oldValue) {
var selected = $(e.currentTarget).val();
});
It depends on the scenario. If you only want to compute the age of a person, then use a function since you want to implement a single specific behaviour.
But if you want to create an object, that contains the date of birth of a person (and possibly other data), allows to modify it, then computing the age could be one of many operations related to the person and it would be sensible to use a class instead.
Classes provide a way to merge together some data and related operations. If you have only one operation on the data then using a function and passing the data as argument you will obtain an equivalent behaviour, with less complex code.
Note that a class of the kind:
class A(object):
def __init__(self, ...):
#initialize
def a_single_method(self, ...):
#do stuff
isn't really a class, it is only a (complicated)function. A legitimate class should always have at least two methods(without counting __init__
).
Due to security violations, organizations may have their own repositories.
set your local repo as below.
npm config set registry https://yourorg-artifactory.com/
I hope this will solve the issue.
CONVERT(column1 USING utf8)
Solves my problem. Where column1 is the column which gives me this error.
If you have any doubt, use merge.
The only differences between a rebase and a merge are:
So the short answer is to pick rebase or merge based on what you want your history to look like.
There are a few factors you should consider when choosing which operation to use.
If so, don't rebase. Rebase destroys the branch and those developers will have broken/inconsistent repositories unless they use git pull --rebase
. This is a good way to upset other developers quickly.
Rebase is a destructive operation. That means, if you do not apply it correctly, you could lose committed work and/or break the consistency of other developer's repositories.
I've worked on teams where the developers all came from a time when companies could afford dedicated staff to deal with branching and merging. Those developers don't know much about Git and don't want to know much. In these teams I wouldn't risk recommending rebasing for any reason.
Some teams use the branch-per-feature model where each branch represents a feature (or bugfix, or sub-feature, etc.) In this model the branch helps identify sets of related commits. For example, one can quickly revert a feature by reverting the merge of that branch (to be fair, this is a rare operation). Or diff a feature by comparing two branches (more common). Rebase would destroy the branch and this would not be straightforward.
I've also worked on teams that used the branch-per-developer model (we've all been there). In this case the branch itself doesn't convey any additional information (the commit already has the author). There would be no harm in rebasing.
Reverting (as in undoing) a rebase is considerably difficult and/or impossible (if the rebase had conflicts) compared to reverting a merge. If you think there is a chance you will want to revert then use merge.
Rebase operations need to be pulled with a corresponding git pull --rebase
. If you are working by yourself you may be able to remember which you should use at the appropriate time. If you are working on a team this will be very difficult to coordinate. This is why most rebase workflows recommend using rebase for all merges (and git pull --rebase
for all pulls).
Assuming you have the following merge:
B -- C
/ \
A--------D
Some people will state that the merge "destroys" the commit history because if you were to look at the log of only the master branch (A -- D) you would miss the important commit messages contained in B and C.
If this were true we wouldn't have questions like this. Basically, you will see B and C unless you explicitly ask not to see them (using --first-parent). This is very easy to try for yourself.
The two approaches merge differently, but it is not clear that one is always better than the other and it may depend on the developer workflow. For example, if a developer tends to commit regularly (e.g. maybe they commit twice a day as they transition from work to home) then there could be a lot of commits for a given branch. Many of those commits might not look anything like the final product (I tend to refactor my approach once or twice per feature). If someone else was working on a related area of code and they tried to rebase my changes it could be a fairly tedious operation.
If you like to alias rm
to rm -rf
to "save time" then maybe rebase is for you.
I always think that someday I will come across a scenario where Git rebase is the awesome tool that solves the problem. Much like I think I will come across a scenario where Git reflog is an awesome tool that solves my problem. I have worked with Git for over five years now. It hasn't happened.
Messy histories have never really been a problem for me. I don't ever just read my commit history like an exciting novel. A majority of the time I need a history I am going to use Git blame or Git bisect anyway. In that case, having the merge commit is actually useful to me, because if the merge introduced the issue, that is meaningful information to me.
I feel obligated to mention that I have personally softened on using rebase although my general advice still stands. I have recently been interacting a lot with the Angular 2 Material project. They have used rebase to keep a very clean commit history. This has allowed me to very easily see what commit fixed a given defect and whether or not that commit was included in a release. It serves as a great example of using rebase correctly.
I had exactly the same issue: After updating to Android Studio 3.1.2 my project wouldn't compile with an AAPT2 error telling me some of my drawables which are referenced by styles.xml
could not be found. Disabling AAPT2 isn't a solution anymore, since the setting is deprecated and will be removed at the end of 2018.
Culprit was an empty line just before the xml decleration in a totally unrelated layout.xml
file... So the layout.xml
file started like this:
//empty line//
<?xml version="1.0" encoding="utf-8"?>
Removed the empty line and everything worked like a charm again. Unbelievable and unlikely, but true.
Android Studio actually gave a warning because the file didn't start with the xml decleration (because of the empty line). But the warning is only visible when the file is opened in the editor.
Class.forName(nameString).newInstance();
Try this,
public static Double[][] multiplicar(Double A[][],Double B[][]){
Double[][] C= new Double[2][2];
int i,j,k;
for (i = 0; i < 2; i++) {
for (j = 0; j < 2; j++) {
C[i][j] = 0.00000;
}
}
for(i=0;i<2;i++){
for(j=0;j<2;j++){
for (k=0;k<2;k++){
C[i][j]+=(A[i][k]*B[k][j]);
}
}
}
return C;
}
If you just have the currency symbol and the number of decimal places, you can use the following helper function, which respects the symbol/amount order, separators etc, only changing the currency symbol itself and the number of decimal places to display to.
public static string FormatCurrency(string currencySymbol, Decimal currency, int decPlaces)
{
NumberFormatInfo localFormat = (NumberFormatInfo)NumberFormatInfo.CurrentInfo.Clone();
localFormat.CurrencySymbol = currencySymbol;
localFormat.CurrencyDecimalDigits = decPlaces;
return currency.ToString("c", localFormat);
}
DateFormat formatter;
formatter = new SimpleDateFormat("dd/MM/yyyy");
Date date = (Date) formatter.parse(str_date);
java.sql.Timestamp timeStampDate = new Timestamp(date.getTime());
Manually add it when you build the query:
SELECT 'Site1' AS SiteName, t1.column, t1.column2
FROM t1
UNION ALL
SELECT 'Site2' AS SiteName, t2.column, t2.column2
FROM t2
UNION ALL
...
EXAMPLE:
DECLARE @t1 TABLE (column1 int, column2 nvarchar(1))
DECLARE @t2 TABLE (column1 int, column2 nvarchar(1))
INSERT INTO @t1
SELECT 1, 'a'
UNION SELECT 2, 'b'
INSERT INTO @t2
SELECT 3, 'c'
UNION SELECT 4, 'd'
SELECT 'Site1' AS SiteName, t1.column1, t1.column2
FROM @t1 t1
UNION ALL
SELECT 'Site2' AS SiteName, t2.column1, t2.column2
FROM @t2 t2
RESULT:
SiteName column1 column2
Site1 1 a
Site1 2 b
Site2 3 c
Site2 4 d
You should use what your FPGA documentation recommends. There is no portable way to initialize register values other than using a reset net. This has a hardware cost associated with it on most synthesis targets.
dots = document.getElementById("txt").value;
dots = Number(dots) + 5;
// from MDN
Number('123') // 123
Number('123') === 123 /// true
Number('12.3') // 12.3
Number('12.00') // 12
Number('123e-1') // 12.3
Number('') // 0
Number(null) // 0
Number('0x11') // 17
Number('0b11') // 3
Number('0o11') // 9
Number('foo') // NaN
Number('100a') // NaN
Number('-Infinity') //-Infinity
You can use the ADB via a terminal to pass the file From Desktop to Emulator.
adb push <file-source-local> <destination-path-remote>
You can also copy file from emulator to Desktop
adb pull <file-source-remote> <destination-path>
How ever you can also use the Android Device Monitor to access files. Click on the Android Icon which can be found in the toolbar itself. It'll take few seconds to load. Once it's loaded, you can see a tab named "File Explorer". Now you could pull/push files from there.
Here a complete example :
Suppose we have a Person class like :
public class Person
{
protected String fname;
protected String lname;
public Person()
{
}
public Person(String fname, String lname)
{
this.fname = fname;
this.lname = lname;
}
public boolean equals(Object objet)
{
if(objet instanceof Person)
{
Person p = (Person) objet;
return (p.getFname().equals(this.fname)) && p.getLname().equals(this.lname));
}
else return super.equals(objet);
}
@Override
public String toString()
{
return "Person(fname : " + getFname + ", lname : " + getLname + ")";
}
/** Getters and Setters **/
}
Now we create a comparator :
import java.util.Comparator;
public class ComparePerson implements Comparator<Person>
{
@Override
public int compare(Person p1, Person p2)
{
if(p1.getFname().equalsIgnoreCase(p2.getFname()))
{
return p1.getLname().compareTo(p2.getLname());
}
return p1.getFname().compareTo(p2.getFname());
}
}
Finally suppose we have a group of persons :
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Group
{
protected List<Person> listPersons;
public Group()
{
this.listPersons = new ArrayList<Person>();
}
public Group(List<Person> listPersons)
{
this.listPersons = listPersons;
}
public void order(boolean asc)
{
Comparator<Person> comp = asc ? new ComparePerson() : Collections.reverseOrder(new ComparePerson());
Collections.sort(this.listPersons, comp);
}
public void display()
{
for(Person p : this.listPersons)
{
System.out.println(p);
}
}
/** Getters and Setters **/
}
Now we try this :
import java.util.ArrayList;
import java.util.List;
public class App
{
public static void main(String[] args)
{
Group g = new Group();
List listPersons = new ArrayList<Person>();
g.setListPersons(listPersons);
Person p;
p = new Person("A", "B");
listPersons.add(p);
p = new Person("C", "D");
listPersons.add(p);
/** you can add Person as many as you want **/
g.display();
g.order(true);
g.display();
g.order(false);
g.display();
}
}
This is what I did in my code, I have just tested and it worked fine, input type="date" does not support to set curdate automatically, so the way I used to overcome this limitation was using PHP code a simple code like this.
<html>
<head></head>
<body>
<form ...>
<?php
echo "<label for='submission_date'>Data de submissão</label>";
echo "<input type='date' name='submission_date' min='2012-01-01' value='" . date('Y-m-d') . "' required/>";
?>
</form>
</body>
</html>
Hope it helps!
You Can not Use the Intent's Context
for Creating Intent. So You need to use your Fragment's
Parent Activity
Context
Intent intent = new Intent(getActivity(),MyClass.class);
I have not seen that exact error before. But I have a guess about the trouble you are encountering. It looks like because the master
and one.one
branches of supery
contain different refs for the subby
submodule, when you merge changes from master
git does not know which ref - v1.0
or v1.1
- should be kept and tracked by the one.one
branch of supery
.
If that is the case, then you need to select the ref that you want and commit that change to resolve the conflict. Which is exactly what you are doing with the reset command.
This is a tricky aspect of tracking different versions of a submodule in different branches of your project. But the submodule ref is just like any other component of your project. If the two different branches continue to track the same respective submodule refs after successive merges, then git should be able to work out the pattern without raising merge conflicts in future merges. On the other hand you if switch submodule refs frequently you may have to put up with a lot of conflict resolving.
The best solution is: from positive to negative or from negative to positive
For negative:
SELECT ABS(a) * -1 AS AbsoluteA, ABS(b) * -1 AS AbsoluteB
FROM YourTable
For positive:
SELECT ABS(a) AS AbsoluteA, ABS(b) AS AbsoluteB
FROM YourTable
There are a few things to change in your edited version:
You've taken the suggestion of using document.myform['whichThing']
a bit too literally. Your form is named "aye", so the code to access the whichThing radio buttons should use that name: `document.aye['whichThing'].
There's no such thing as an action
attribute for the <input>
tag. Use onclick
instead: <input name="Submit" type="submit" value="Update" onclick="handleClick();return false"/>
Obtaining and cancelling an Event object in a browser is a very involved process. It varies a lot by browser type and version. IE and Firefox handle these things very differently, so a simple event.preventDefault()
won't work... in fact, the event variable probably won't even be defined because this is an onclick handler from a tag. This is why Stephen above is trying so hard to suggest a framework. I realize you want to know the mechanics, and I recommend google for that. In this case, as a simple workaround, use return false
in the onclick tag as in number 2 above (or return false from the function as stephen suggested).
Because of #3, get rid of everything not the alert statement in your handler.
The code should now look like:
function handleClick()
{
alert("Favorite weird creature: "+getRadioButtonValue(document.aye['whichThing']));
}
</script>
</head>
<body>
<form name="aye">
<input name="Submit" type="submit" value="Update" onclick="handleClick();return false"/>
Which of the following do you like best?
<p><input type="radio" name="whichThing" value="slithy toves" />Slithy toves</p>
<p><input type="radio" name="whichThing" value="borogoves" />Borogoves</p>
<p><input type="radio" name="whichThing" value="mome raths" />Mome raths</p>
</form>
Probably there is a table, which stores the friend <-> user relation, say "frnd_list", having fields 'user_id','frnd_id'.
Whenever a user adds another user as a friend, two new rows are created.
For instance, suppose my id is 'deep9c' and I add a user having id 'akash3b' as my friend, then two new rows are created in table "frnd_list" with values ('deep9c','akash3b') and ('akash3b','deep9c').
Now when showing the friends-list to a particular user, a simple sql would do that: "select frnd_id from frnd_list where user_id=" where is the id of the logged-in user (stored as a session-attribute).
Or this in windows powershell
$env:RANDFILE=".rnd"
You can simply use Arrays.sort()
array.sort((a,b) => a.title.rendered.localeCompare(b.title.rendered));
Working Example :
var array = [{"id":3645,"date":"2018-07-05T13:13:37","date_gmt":"2018-07-05T13:13:37","guid":{"rendered":""},"modified":"2018-07-05T13:13:37","modified_gmt":"2018-07-05T13:13:37","slug":"vpwin","status":"publish","type":"matrix","link":"","title":{"rendered":"VPWIN"},"content":{"rendered":"","protected":false},"featured_media":0,"parent":0,"template":"","better_featured_image":null,"acf":{"domain":"SMB","ds_rating":"3","dt_rating":""},},{"id":3645,"date":"2018-07-05T13:13:37","date_gmt":"2018-07-05T13:13:37","guid":{"rendered":""},"modified":"2018-07-05T13:13:37","modified_gmt":"2018-07-05T13:13:37","slug":"vpwin","status":"publish","type":"matrix","link":"","title":{"rendered":"adfPWIN"},"content":{"rendered":"","protected":false},"featured_media":0,"parent":0,"template":"","better_featured_image":null,"acf":{"domain":"SMB","ds_rating":"3","dt_rating":""}},{"id":3645,"date":"2018-07-05T13:13:37","date_gmt":"2018-07-05T13:13:37","guid":{"rendered":""},"modified":"2018-07-05T13:13:37","modified_gmt":"2018-07-05T13:13:37","slug":"vpwin","status":"publish","type":"matrix","link":"","title":{"rendered":"bbfPWIN"},"content":{"rendered":"","protected":false},"featured_media":0,"parent":0,"template":"","better_featured_image":null,"acf":{"domain":"SMB","ds_rating":"3","dt_rating":""}}];_x000D_
array.sort((a,b) => a.title.rendered.localeCompare(b.title.rendered));_x000D_
_x000D_
console.log(array);
_x000D_
You can't turn an existing string "raw". The r
prefix on literals is understood by the parser; it tells it to ignore escape sequences in the string. However, once a string literal has been parsed, there's no difference between a raw string and a "regular" one. If you have a string that contains a newline, for instance, there's no way to tell at runtime whether that newline came from the escape sequence \n
, from a literal newline in a triple-quoted string (perhaps even a raw one!), from calling chr(10)
, by reading it from a file, or whatever else you might be able to come up with. The actual string object constructed from any of those methods looks the same.
Why all people want to use '==' instead of simple '=' ? It is bad habit! It used only in [[ ]] expression. And in (( )) too. But you may use just = too! It work well in any case. If you use numbers, not strings use not parcing to strings and then compare like strings but compare numbers. like that
let -i i=5 # garantee that i is nubmber
test $i -eq 5 && echo "$i is equal 5" || echo "$i not equal 5"
It's match better and quicker. I'm expert in C/C++, Java, JavaScript. But if I use bash i never use '==' instead '='. Why you do so?
If you didn't push the update in remote then the simple solution is remove last local commit using following command: git reset HEAD^
. Then add all files and commit again.
Do the following in the App.config file,
connectionStrings
element is after the configSections
element.startup
element after the connectionStrings
element.<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=4.3.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</configSections>
<connectionStrings>
<add name="SchedulingContext" connectionString="Data Source=XXX\SQL2008R2DEV;Initial Catalog=YYY;Persist Security Info=True;User ID=sa;Password=XXX" providerName="System.Data.SqlClient"/>
</connectionStrings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
</configuration>
$.each(top_brands, function() {
var key = Object.keys(this)[0];
var value = this[key];
brand_options.append($("<option />").val(key).text(key + " " + value));
});
For what it's worth, you can do {$varname|@debug_print_var}
to get a var_dump()
-esque output for your variable.
You could define a mapping of air pressure to servo angle, for example:
def calc_angle(pressure, min_p=1000, max_p=1200): return 360 * ((pressure - min_p) / float(max_p - min_p)) angle = calc_angle(pressure)
This will linearly convert pressure
values between min_p
and max_p
to angles between 0 and 360 (you could include min_a
and max_a
to constrain the angle, too).
To pick a data structure, I wouldn't use a list but you could look up values in a dictionary:
d = {1000:0, 1001: 1.8, ...} angle = d[pressure]
but this would be rather time-consuming to type out!
Assuming you know what you're doing, I suspect IE6 is not interpreting the file's encoding correctly, and hence not recognising the non-ASCII characters in the file:
(It "smells" wrong though, I'd look into doing the sorting, say on the server using something that's locale-aware... but anyway...)
Nested JSON
object
var data = {
view:{
type: 'success', note:'Updated successfully',
},
};
You can parse this data.view.type
and data.view.note
JSON
Object and inside Array
var data = {
view: [
{type: 'success', note:'updated successfully'}
],
};
You can parse this data.view[0].type
and data.view[0].note
Answer from woodshy worked for me, and it is simpler than the answer by Ungureanu Liviu since it does not use RelativeLayout
.
I am giving my layout for clarity:
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
<Button
android:layout_width = "80dp"
android:layout_weight = "0"
android:layout_height = "wrap_content"
android:text="<"/>
<TextView
android:layout_width = "fill_parent"
android:layout_height = "wrap_content"
android:layout_weight = "1"/>
<Button
android:layout_width = "80dp"
android:layout_weight = "0"
android:layout_height = "wrap_content"
android:text=">"/>
</LinearLayout>
pattern = /[a-zA-Z]/
puts "[a-zA-Z]: #{pattern.match("mine blossom")}" OK
puts "[a-zA-Z]: #{pattern.match("456")}"
puts "[a-zA-Z]: #{pattern.match("")}"
puts "[a-zA-Z]: #{pattern.match("#$%^&*")}"
puts "[a-zA-Z]: #{pattern.match("#$%^&*A")}" OK
-w
is the GCC-wide option to disable warning messages.
The error was due to the way that I configured the Application Pool in IIS.
My web service uses an Application Tool configured for v2.0.50727. This resulted in the error message.
When I changed it to v4.0.30319, I did not get the error.
I face same error for ejs, then i just run node install ejs
This will install ejs again.
and then also run npm install
to install node_modules again.
That's work for me.
Take a look at my jquery videoBG plugin
http://syddev.com/jquery.videoBG/
Make any HTML5 video a site background... has an image fallback for browsers that don't support html5
Really easy to use
Let me know if you need any help.
I already wrote up the answer to this but it seems to have been deleted. The issue was that YUI added background-color:white
to the HTML element. I overwrote that and everything was easy to handle from there.
There is no way to delete or read the past history.
You could try going around it by emulating history in your own memory and calling history.pushState
everytime window popstate
event is emitted (which is proposed by the currently accepted Mike's answer), but it has a lot of disadvantages that will result in even worse UX than not supporting the browser history at all in your dynamic web app, because:
So even if you try going around it by building virtual history, it's very likely that it can also lead into a situation where you have blank history states (to which going back/forward does nothing), or where that going back/forward skips some of your history states totally.
Generally speaking a schema in oracle is the same as an user. Oracle Database automatically creates a schema when you create a user. A file with the DDL file extension is an SQL Data Definition Language file.
Creating new user (using SQL Plus)
Basic SQL Plus commands:
- connect: connects to a database
- disconnect: logs off but does not exit
- exit: exists
Open SQL Plus and log:
/ as sysdba
The sysdba is a role and is like "root" on unix or "Administrator" on Windows. It sees all, can do all. Internally, if you connect as sysdba, your schema name will appear to be SYS.
Create an user:
SQL> create user johny identified by 1234;
View all users and check if the user johny is there:
SQL> select username from dba_users;
If you try to login as johny now you would get an error:
ERROR:
ORA-01045: user JOHNY lacks CREATE SESSION privilege; logon denied
The user to login needs at least create session priviledge so we have to grant this privileges to the user:
SQL> grant create session to johny;
Now you are able to connect as the user johny:
username: johny
password: 1234
To get rid of the user you can drop it:
SQL> drop user johny;
That was basic example to show how to create an user. It might be more complex. Above we created an user whose objects are stored in the database default tablespace. To have database tidy we should place users objects to his own space (tablespace is an allocation of space in the database that can contain schema objects).
Show already created tablespaces:
SQL> select tablespace_name from dba_tablespaces;
Create tablespace:
SQL> create tablespace johny_tabspace
2 datafile 'johny_tabspace.dat'
3 size 10M autoextend on;
Create temporary tablespace (Temporaty tablespace is an allocation of space in the database that can contain transient data that persists only for the duration of a session. This transient data cannot be recovered after process or instance failure.):
SQL> create temporary tablespace johny_tabspace_temp
2 tempfile 'johny_tabspace_temp.dat'
3 size 5M autoextend on;
Create the user:
SQL> create user johny
2 identified by 1234
3 default tablespace johny_tabspace
4 temporary tablespace johny_tabspace_temp;
Grant some privileges:
SQL> grant create session to johny;
SQL> grant create table to johny;
SQL> grant unlimited tablespace to johny;
Login as johny and check what privileges he has:
SQL> select * from session_privs;
PRIVILEGE
----------------------------------------
CREATE SESSION
UNLIMITED TABLESPACE
CREATE TABLE
With create table privilege the user can create tables:
SQL> create table johny_table
2 (
3 id int not null,
4 text varchar2(1000),
5 primary key (id)
6 );
Insert data:
SQL> insert into johny_table (id, text)
2 values (1, 'This is some text.');
Select:
SQL> select * from johny_table;
ID TEXT
--------------------------
1 This is some text.
To get DDL data you can use DBMS_METADATA package that "provides a way for you to retrieve metadata from the database dictionary as XML or creation DDL and to submit the XML to re-create the object.". (with help from http://www.dba-oracle.com/oracle_tips_dbms_metadata.htm)
For table:
SQL> set pagesize 0
SQL> set long 90000
SQL> set feedback off
SQL> set echo off
SQL> SELECT DBMS_METADATA.GET_DDL('TABLE',u.table_name) FROM USER_TABLES u;
Result:
CREATE TABLE "JOHNY"."JOHNY_TABLE"
( "ID" NUMBER(*,0) NOT NULL ENABLE,
"TEXT" VARCHAR2(1000),
PRIMARY KEY ("ID")
USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255
STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT FLASH_CACHE DE
FAULT CELL_FLASH_CACHE DEFAULT)
TABLESPACE "JOHNY_TABSPACE" ENABLE
) SEGMENT CREATION IMMEDIATE
PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255 NOCOMPRESS LOGGING
STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT FLASH_CACHE DE
FAULT CELL_FLASH_CACHE DEFAULT)
TABLESPACE "JOHNY_TABSPACE"
For index:
SQL> set pagesize 0
SQL> set long 90000
SQL> set feedback off
SQL> set echo off
SQL> SELECT DBMS_METADATA.GET_DDL('INDEX',u.index_name) FROM USER_INDEXES u;
Result:
CREATE UNIQUE INDEX "JOHNY"."SYS_C0013353" ON "JOHNY"."JOHNY_TABLE" ("ID")
PCTFREE 10 INITRANS 2 MAXTRANS 255
STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT FLASH_CACHE DE
FAULT CELL_FLASH_CACHE DEFAULT)
TABLESPACE "JOHNY_TABSPACE"
More information:
DDL
DBMS_METADATA
Schema objects
Differences between schema and user
Privileges
Creating user/schema
Creating tablespace
SQL Plus commands
Powershell provides a lot of built-in support for common parameter scenarios, including mandatory parameters, optional parameters, "switch" (aka flag) parameters, and "parameter sets."
By default, all parameters are optional. The most basic approach is to simply check each one for $null
, then implement whatever logic you want from there. This is basically what you have already shown in your sample code.
If you want to learn about all of the special support that Powershell can give you, check out these links:
.communicate()
writes input (there is no input in this case so it just closes subprocess' stdin to indicate to the subprocess that there is no more input), reads all output, and waits for the subprocess to exit.
The exception EOFError is raised in the child process by raw_input()
(it expected data but got EOF (no data)).
p.stdout.read()
hangs forever because it tries to read all output from the child at the same time as the child waits for input (raw_input()
) that causes a deadlock.
To avoid the deadlock you need to read/write asynchronously (e.g., by using threads or select) or to know exactly when and how much to read/write, for example:
from subprocess import PIPE, Popen
p = Popen(["python", "-u", "1st.py"], stdin=PIPE, stdout=PIPE, bufsize=1)
print p.stdout.readline(), # read the first line
for i in range(10): # repeat several times to show that it works
print >>p.stdin, i # write input
p.stdin.flush() # not necessary in this case
print p.stdout.readline(), # read output
print p.communicate("n\n")[0], # signal the child to exit,
# read the rest of the output,
# wait for the child to exit
Note: it is a very fragile code if read/write are not in sync; it deadlocks.
Beware of block-buffering issue (here it is solved by using "-u" flag that turns off buffering for stdin, stdout in the child).
Just used @badcat's answer in a modified version, using subprocess.check_output()
:
import subprocess
revision = subprocess.check_output("svn info | awk '/^Revision:/ {print $2}'", shell=True).strip()
I believe you can also, install and use pysvn if you want to use python to interface with svn.
I'm going to heavily quote the Object documentation here, because I think it has some great explanations. I encourage you to read it, and also the documentation for these methods as they're overridden in other classes, like String.
Side note: if you want to try these out for yourself on different objects, use something like this:
class Object
def all_equals(o)
ops = [:==, :===, :eql?, :equal?]
Hash[ops.map(&:to_s).zip(ops.map {|s| send(s, o) })]
end
end
"a".all_equals "a" # => {"=="=>true, "==="=>true, "eql?"=>true, "equal?"=>false}
==
— generic "equality"At the Object level,
==
returns true only ifobj
andother
are the same object. Typically, this method is overridden in descendant classes to provide class-specific meaning.
This is the most common comparison, and thus the most fundamental place where you (as the author of a class) get to decide if two objects are "equal" or not.
===
— case equalityFor class Object, effectively the same as calling
#==
, but typically overridden by descendants to provide meaningful semantics in case statements.
This is incredibly useful. Examples of things which have interesting ===
implementations:
So you can do things like:
case some_object
when /a regex/
# The regex matches
when 2..4
# some_object is in the range 2..4
when lambda {|x| some_crazy_custom_predicate }
# the lambda returned true
end
See my answer here for a neat example of how case
+Regex
can make code a lot cleaner. And of course, by providing your own ===
implementation, you can get custom case
semantics.
eql?
— Hash
equalityThe
eql?
method returns true ifobj
andother
refer to the same hash key. This is used byHash
to test members for equality. For objects of classObject
,eql?
is synonymous with==
. Subclasses normally continue this tradition by aliasingeql?
to their overridden==
method, but there are exceptions.Numeric
types, for example, perform type conversion across==
, but not acrosseql?
, so:1 == 1.0 #=> true 1.eql? 1.0 #=> false
So you're free to override this for your own uses, or you can override ==
and use alias :eql? :==
so the two methods behave the same way.
equal?
— identity comparisonUnlike
==
, theequal?
method should never be overridden by subclasses: it is used to determine object identity (that is,a.equal?(b)
iffa
is the same object asb
).
This is effectively pointer comparison.
Well, this may not be the most elegant solution (semantically), but in some cases it'll work without any drawbacks: Instead of padding, use a transparent border on the parent element. The absolute positioned child elements will honor the border and it'll be rendered exactly the same (except you're using the border of the parent element for styling).
If you want to avoid writing all of this everytime, you can define a function :
def run(filename):
exec(open(filename).read())
and then call it
run('filename.py')
It is standard matplotlib.pyplot:
...
import matplotlib.pyplot as plt
plt.ylim(10, 40)
Or simpler, as mwaskom comments below:
ax.set(ylim=(10, 40))
In your case either the record doesn't exist with the userid=2
or it may contain a null value in first column, because if no value is found for the query result used in SQL command, ExecuteScalar()
returns null
.
this is my working example Java code to encode QR code using ZXing with UTF-8 encoding, please note: you will need to change the path and utf8 data to your path and language characters
package com.mypackage.qr;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.util.Hashtable;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.*;
public class CreateQR {
public static void main(String[] args)
{
Charset charset = Charset.forName("UTF-8");
CharsetEncoder encoder = charset.newEncoder();
byte[] b = null;
try {
// Convert a string to UTF-8 bytes in a ByteBuffer
ByteBuffer bbuf = encoder.encode(CharBuffer.wrap("utf 8 characters - i used hebrew, but you should write some of your own language characters"));
b = bbuf.array();
} catch (CharacterCodingException e) {
System.out.println(e.getMessage());
}
String data;
try {
data = new String(b, "UTF-8");
// get a byte matrix for the data
BitMatrix matrix = null;
int h = 100;
int w = 100;
com.google.zxing.Writer writer = new MultiFormatWriter();
try {
Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>(2);
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
matrix = writer.encode(data,
com.google.zxing.BarcodeFormat.QR_CODE, w, h, hints);
} catch (com.google.zxing.WriterException e) {
System.out.println(e.getMessage());
}
// change this path to match yours (this is my mac home folder, you can use: c:\\qr_png.png if you are on windows)
String filePath = "/Users/shaybc/Desktop/OutlookQR/qr_png.png";
File file = new File(filePath);
try {
MatrixToImageWriter.writeToFile(matrix, "PNG", file);
System.out.println("printing to " + file.getAbsolutePath());
} catch (IOException e) {
System.out.println(e.getMessage());
}
} catch (UnsupportedEncodingException e) {
System.out.println(e.getMessage());
}
}
}