If you don't have an array but you are trying to use your observable like an array even though it's a stream of objects, this won't work natively. I show how to fix this below assuming you only care about adding objects to the observable, not deleting them.
If you are trying to use an observable whose source is of type BehaviorSubject, change it to ReplaySubject then in your component subscribe to it like this:
this.messages$ = this.chatService.messages$.pipe(scan((acc, val) => [...acc, val], []));
<div class="message-list" *ngFor="let item of messages$ | async">
It's ugly, but I achieved a semblance of this like so:
Dockerfile:
FROM foo
COPY ./m2/ /root/.m2
RUN stuff
imageBuild.sh:
docker build . -t barImage
container="$(docker run -d barImage)"
rm -rf ./m2
docker cp "$container:/root/.m2" ./m2
docker rm -f "$container"
I have a java build that downloads the universe into /root/.m2, and did so every single time. imageBuild.sh
copies the contents of that folder onto the host after the build, and Dockerfile
copies them back into the image for the next build.
This is something like how a volume would work (i.e. it persists between builds).
Ultimately, we are trying to get to this.
<div style="display: flex; justify-content: center;">
<button ion-button>Login</button>
</div>
From the documentation for strtotime()
:
Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed.
In your date string, you have 12-16-2013
. 16
isn't a valid month, and hence strtotime()
returns false
.
Since you can't use DateTime class, you could manually replace the -
with /
using str_replace()
to convert the date string into a format that strtotime()
understands:
$date = '2-16-2013';
echo date('Y-m-d', strtotime(str_replace('-','/', $date))); // => 2013-02-16
You can use
$objWorksheet->getActiveSheet()->getRowDimension('1')->setRowHeight(40);
$objWorksheet->getActiveSheet()->getColumnDimension('A')->setWidth(100);
or define auto-size:
$objWorksheet->getRowDimension('1')->setRowHeight(-1);
To find the specific error run this:
SHOW ENGINE INNODB STATUS;
And look in the LATEST FOREIGN KEY ERROR
section.
The data type for the child column must match the parent column exactly. For example, since medicalhistory.MedicalHistoryID
is an INT
, Patient.MedicalHistory
also needs to be an INT
, not a SMALLINT
.
Also, you should run the query set foreign_key_checks=0
before running the DDL so you can create the tables in an arbitrary order rather than needing to create all parent tables before the relevant child tables.
USE join to get 0 count in the result using GROUP BY.
simply 'join' does Inner join in MS SQL so , Go for left or right join.
If the table which contains the primary key is mentioned first in the QUERY then use LEFT join else RIGHT join.
EG:
select WARDNO,count(WARDCODE) from MAIPADH
right join MSWARDH on MSWARDH.WARDNO= MAIPADH.WARDCODE
group by WARDNO
.
select WARDNO,count(WARDCODE) from MSWARDH
left join MAIPADH on MSWARDH.WARDNO= MAIPADH.WARDCODE group by WARDNO
Take group by from the table which has Primary key and count from the another table which has actual entries/details.
1) use for tommorow's date startDate: '+1d'
2) use for yesterday's date startDate: '-1d'
3) use for today's date startDate: new Date()
As @Ravi_MCA mentioned, /users?ids[]=id1&ids[]=id2
worked for me, too.
{"params":["arg1", "arg2", ...]}
You can even use JSON object instead of array.
You should try this syntax - assuming you want to have @OrderID
as a parameter for your stored procedure:
CREATE PROCEDURE dbo.YourStoredProcNameHere
@OrderID INT
AS
BEGIN
DECLARE @OrderItemID AS INT
DECLARE @AppointmentID AS INT
DECLARE @PurchaseOrderID AS INT
DECLARE @PurchaseOrderItemID AS INT
DECLARE @SalesOrderID AS INT
DECLARE @SalesOrderItemID AS INT
SELECT @OrderItemID = OrderItemID
FROM [OrderItem]
WHERE OrderID = @OrderID
SELECT @AppointmentID = AppoinmentID
FROM [Appointment]
WHERE OrderID = @OrderID
SELECT @PurchaseOrderID = PurchaseOrderID
FROM [PurchaseOrder]
WHERE OrderID = @OrderID
END
OF course, that only works if you're returning exactly one value (not multiple values!)
This project should be helpful - maps touch events to click events in a way that allows jQuery UI to work on iPad and iPhone without any changes. Just add the JS to any existing project.
public List<tbltask> gettaskssdata(int? c, int? userid, string a, string StartDate, string EndDate, int? ProjectID, int? statusid)_x000D_
{_x000D_
List<tbltask> tbtask = new List<tbltask>();_x000D_
DateTime sdate = (StartDate != "") ? Convert.ToDateTime(StartDate).Date : new DateTime();_x000D_
DateTime edate = (EndDate != "") ? Convert.ToDateTime(EndDate).Date : new DateTime();_x000D_
tbtask = entity.tbltasks.Include(x => x.tblproject).Include(x => x.tbUser)._x000D_
Where(x => x.tblproject.company_id == c_x000D_
&& (ProjectID == 0 || ProjectID == x.tblproject.ProjectId)_x000D_
&& (statusid == 0 || statusid == x.tblstatu.StatusId)_x000D_
&& (a == "" || (x.TaskName.Contains(a) || x.tbUser.User_name.Contains(a)))_x000D_
&& ((StartDate == "" && EndDate == "") || ((x.StartDate >= sdate && x.EndDate <= edate)))).ToList();_x000D_
_x000D_
_x000D_
_x000D_
return tbtask;_x000D_
_x000D_
_x000D_
}
_x000D_
this my query for search records based on searchdata and between start to end date
I had some decoding issues with HtmlAgility and I didn't want to invest time investigating it.
Instead I used that utility from the Microsoft Team Foundation API:
var text = HtmlFilter.ConvertToPlainText(htmlContent);
The solution here that everyone likes seems to very intense... personally I think it's much easier to do something like this:
var holidays = ["12/24/2012", "12/25/2012", "1/1/2013",
"5/27/2013", "7/4/2013", "9/2/2013", "11/28/2013",
"11/29/2013", "12/24/2013", "12/25/2013"];
$( "#requestShipDate" ).datepicker({
beforeShowDay: function(date){
show = true;
if(date.getDay() == 0 || date.getDay() == 6){show = false;}//No Weekends
for (var i = 0; i < holidays.length; i++) {
if (new Date(holidays[i]).toString() == date.toString()) {show = false;}//No Holidays
}
var display = [show,'',(show)?'':'No Weekends or Holidays'];//With Fancy hover tooltip!
return display;
}
});
This way your dates are human readable. It's not really that different it just makes more sense to me this way.
Using ES6 syntax, if you need a "pipeline" like process where you pass the same object through a series of functions (in my case, a HTML abstract syntax tree), you can use for...of
to call each pipe function in a given array:
const setMainElement = require("./set-main-element.js")
const cacheImages = require("./cache-images.js")
const removeElements = require("./remove-elements.js")
let htmlAst = {}
const pipeline = [
setMainElement,
cacheImages,
removeElements,
(htmlAst) => {
// Using a dynamic closure.
},
]
for (const pipe of pipeline) {
pipe(htmlAst)
}
Here is how to do it using TCP IP protocol :
// Printer IP Address and communication port
string ipAddress = "10.3.14.42";
int port = 9100;
// ZPL Command(s)
string ZPLString =
"^XA" +
"^FO50,50" +
"^A0N50,50" +
"^FDHello, World!^FS" +
"^XZ";
try
{
// Open connection
System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient();
client.Connect(ipAddress, port);
// Write ZPL String to connection
System.IO.StreamWriter writer =
new System.IO.StreamWriter(client.GetStream());
writer.Write(ZPLString);
writer.Flush();
// Close Connection
writer.Close();
client.Close();
}
catch (Exception ex)
{
// Catch Exception
}
Source : ZEBRA WEBSITE
You can create a new dict for each pair and merge it with the previous dict:
reduce(lambda p, q: {**p, **{q[0]: q[1]}}, bla bla bla, {})
Obviously this approaches requires reduce
from functools
.
I have defined one pattern to look for any of the ASCII Special Characters ranging between 032 to 126 except the alpha-numeric. You may use something like the one below:
To find any Special Character:
[ -\/:-@\[-\`{-~]
To find minimum of 1 and maximum of any count:
(?=.*[ -\/:-@\[-\`{-~]{1,})
These patterns have Special Characters ranging between 032 to 047, 058 to 064, 091 to 096, and 123 to 126.
In testng.xml file, remove "." from tag "" class name if you are not using packages.
Suppose your form is named form1:
function selectValue(val)
{
var lc = document.form1.leaveCode;
for (i=0; i<lc.length; i++)
{
if (lc.options[i].value == val)
{
lc.selectedIndex = i;
return;
}
}
}
For Bootstrap 4 you may have to use .modal-backdrop.show
and play around with !important
flag on both background-color
and opacity
.
E.g.
.modal-backdrop.show {
background-color: #f00;
opacity: 0.75;
}
you could use inherit
#one {width:500px;height:300px;}
#two {width:inherit;height:inherit;}
#three {width:inherit;height:inherit;}
You could change the @RequestParam type to an Integer and make it not required. This would allow your request to succeed, but it would then be null. You could explicitly set it to your default value in the controller method:
@RequestMapping(value = "/test", method = RequestMethod.POST)
@ResponseBody
public void test(@RequestParam(value = "i", required=false) Integer i) {
if(i == null) {
i = 10;
}
// ...
}
I have removed the defaultValue from the example above, but you may want to include it if you expect to receive requests where it isn't set at all:
http://example.com/test
* Secondary way : *
If you don't need [id] to be as Primary key,
Remove its primary key attribute:
on your DataSet > TableAdapter > right click on [id] column > select Delete key ...
Problem will be fixed.
you can save the xlsx file as a tab-delimited text file and do
BULK INSERT TableName
FROM 'C:\SomeDirectory\my table.txt'
WITH
(
FIELDTERMINATOR = '\t',
ROWTERMINATOR = '\n'
)
GO
I tray order by with problematic column and i find rows with column.
SELECT
D.UNIT_CODE,
D.CUATM,
D.CAPITOL,
D.RIND,
D.COL1 AS COL1
FROM
VW_DATA_ALL_GC D
WHERE
(D.PERIOADA IN (:pPERIOADA)) AND
(D.FORM = 62)
AND D.COL1 IS NOT NULL
-- AND REGEXP_LIKE (D.COL1, '\[\[:alpha:\]\]')
-- AND REGEXP_LIKE(D.COL1, '\[\[:digit:\]\]')
--AND REGEXP_LIKE(TO_CHAR(D.COL1), '\[^0-9\]+')
GROUP BY
D.UNIT_CODE,
D.CUATM,
D.CAPITOL,
D.RIND ,
D.COL1
ORDER BY
D.COL1
this will be slow, but if it is a one time thing, try...
select * from parameters where name like '%'+char(13)+'%' or name like '%'+char(10)+'%'
Note that the ANSI SQL string concatenation operator is "||", so it may need to be:
select * from parameters where name like '%' || char(13) || '%' or name like '%' || char(10) || '%'
When it comes to Muhammad Mehdi's answer, it is better to do:
private void salary_texbox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
Regex regex = new Regex ( "[^0-9]+" );
if(regex.IsMatch(e.Text))
{
MessageBox.Show("Error");
}
}
Because when comparing with the TextCompositionEventArgs it gets also the last character, while with the textbox.Text it does not. With textbox, the error will show after next inserted character.
I believe you can do this using a cast:
float f_val = 3.6f;
int i_val = (int) f_val;
<mvc:annotation-driven />
<mvc:default-servlet-handler />
<mvc:resources mapping="/resources/**" location="/resources/" />
<context:component-scan base-package="com.tridenthyundai.ains" />
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="/WEB-INF/messages" />
</bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/pages/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
In case you do need to define dataSource()
, for example when you have multiple data sources, you can use:
@Autowired Environment env;
@Primary
@Bean
public DataSource customDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(env.getProperty("custom.datasource.driver-class-name"));
dataSource.setUrl(env.getProperty("custom.datasource.url"));
dataSource.setUsername(env.getProperty("custom.datasource.username"));
dataSource.setPassword(env.getProperty("custom.datasource.password"));
return dataSource;
}
By setting up the dataSource
yourself (instead of using DataSourceBuilder
), it fixed my problem which you also had.
The always knowledgeable Baeldung has a tutorial which explains in depth.
This is by far the best post for exporting to excel from SQL:
http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=49926
To quote from user madhivanan
,
Apart from using DTS and Export wizard, we can also use this query to export data from SQL Server2000 to Excel
Create an Excel file named testing having the headers same as that of table columns and use these queries
1 Export data to existing EXCEL file from SQL Server table
insert into OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=D:\testing.xls;',
'SELECT * FROM [SheetName$]') select * from SQLServerTable
2 Export data from Excel to new SQL Server table
select *
into SQLServerTable FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=D:\testing.xls;HDR=YES',
'SELECT * FROM [Sheet1$]')
3 Export data from Excel to existing SQL Server table (edited)
Insert into SQLServerTable Select * FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=D:\testing.xls;HDR=YES',
'SELECT * FROM [SheetName$]')
4 If you dont want to create an EXCEL file in advance and want to export data to it, use
EXEC sp_makewebtask
@outputfile = 'd:\testing.xls',
@query = 'Select * from Database_name..SQLServerTable',
@colheaders =1,
@FixedFont=0,@lastupdated=0,@resultstitle='Testing details'
(Now you can find the file with data in tabular format)
5 To export data to new EXCEL file with heading(column names), create the following procedure
create procedure proc_generate_excel_with_columns
(
@db_name varchar(100),
@table_name varchar(100),
@file_name varchar(100)
)
as
--Generate column names as a recordset
declare @columns varchar(8000), @sql varchar(8000), @data_file varchar(100)
select
@columns=coalesce(@columns+',','')+column_name+' as '+column_name
from
information_schema.columns
where
table_name=@table_name
select @columns=''''''+replace(replace(@columns,' as ',''''' as '),',',',''''')
--Create a dummy file to have actual data
select @data_file=substring(@file_name,1,len(@file_name)-charindex('\',reverse(@file_name)))+'\data_file.xls'
--Generate column names in the passed EXCEL file
set @sql='exec master..xp_cmdshell ''bcp " select * from (select '+@columns+') as t" queryout "'+@file_name+'" -c'''
exec(@sql)
--Generate data in the dummy file
set @sql='exec master..xp_cmdshell ''bcp "select * from '+@db_name+'..'+@table_name+'" queryout "'+@data_file+'" -c'''
exec(@sql)
--Copy dummy file to passed EXCEL file
set @sql= 'exec master..xp_cmdshell ''type '+@data_file+' >> "'+@file_name+'"'''
exec(@sql)
--Delete dummy file
set @sql= 'exec master..xp_cmdshell ''del '+@data_file+''''
exec(@sql)
After creating the procedure, execute it by supplying database name, table name and file path:
EXEC proc_generate_excel_with_columns 'your dbname', 'your table name','your file path'
Its a whomping 29 pages but that is because others show various other ways as well as people asking questions just like this one on how to do it.
Follow that thread entirely and look at the various questions people have asked and how they are solved. I picked up quite a bit of knowledge just skimming it and have used portions of it to get expected results.
To update single cells
A member also there Peter Larson posts the following: I think one thing is missing here. It is great to be able to Export and Import to Excel files, but how about updating single cells? Or a range of cells?
This is the principle of how you do manage that
update OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=c:\test.xls;hdr=no',
'SELECT * FROM [Sheet1$b7:b7]') set f1 = -99
You can also add formulas to Excel using this:
update OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=c:\test.xls;hdr=no',
'SELECT * FROM [Sheet1$b7:b7]') set f1 = '=a7+c7'
Exporting with column names using T-SQL
Member Mladen Prajdic also has a blog entry on how to do this here
References: www.sqlteam.com (btw this is an excellent blog / forum for anyone looking to get more out of SQL Server). For error referencing I used this
If you get the following error:
OLE DB provider 'Microsoft.Jet.OLEDB.4.0' cannot be used for distributed queries
Then run this:
sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
sp_configure 'Ad Hoc Distributed Queries', 1;
GO
RECONFIGURE;
GO
Judging by the documentation for date/time functions, you should be able to do something like:
SELECT * FROM FOO
WHERE MY_DATE_FIELD >= NOW() - INTERVAL 1 DAY
First of all, I think it's usually \r\n
, second of all, those are not the same on all systems. That will only work on windows. It's kind-of annoying trying to figure out how to replace new lines because different systems treat them differently (see here). You might have better luck with just \n
.
You can use itertools.repeat
with operator.methodcaller
to call the __call__
method of the function N times. Here is an example of a generator function doing it:
from itertools import repeat
from operator import methodcaller
def call_n_times(function, n):
yield from map(methodcaller('__call__'), repeat(function, n))
Example of usage:
import random
from functools import partial
throw_dice = partial(random.randint, 1, 6)
result = call_n_times(throw_dice, 10)
print(list(result))
# [6, 3, 1, 2, 4, 6, 4, 1, 4, 6]
typeid(T).name()
is implementation defined and doesn't guarantee human readable string.
Reading cppreference.com :
Returns an implementation defined null-terminated character string containing the name of the type. No guarantees are given, in particular, the returned string can be identical for several types and change between invocations of the same program.
...
With compilers such as gcc and clang, the returned string can be piped through c++filt -t to be converted to human-readable form.
But in some cases gcc doesn't return right string. For example on my machine I have gcc whith -std=c++11
and inside template function typeid(T).name()
returns "j"
for "unsigned int"
. It's so called mangled name. To get real type name, use
abi::__cxa_demangle() function (gcc only):
#include <string>
#include <cstdlib>
#include <cxxabi.h>
template<typename T>
std::string type_name()
{
int status;
std::string tname = typeid(T).name();
char *demangled_name = abi::__cxa_demangle(tname.c_str(), NULL, NULL, &status);
if(status == 0) {
tname = demangled_name;
std::free(demangled_name);
}
return tname;
}
Default html color code like this:
Red #FF0000 rgb(255, 0, 0)
Maroon #800000 rgb(128, 0, 0)
Yellow #FFFF00 rgb(255, 255, 0)
Olive #808000 rgb(128, 128, 0)
Blue #0000FF rgb(0, 0, 255)
Navy #000080 rgb(0, 0, 128)
Fuchsia #FF00FF rgb(255, 0, 255)
Purple #800080 rgb(128, 0, 128)
The code you posted works for me with the latest version of Mockito and Powermockito. Maybe you haven't prepared A? Try this:
A.java
public class A {
private final String test;
public A(String test) {
this.test = test;
}
public String check() {
return "checked " + this.test;
}
}
MockA.java
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
@RunWith(PowerMockRunner.class)
@PrepareForTest(A.class)
public class MockA {
@Test
public void test_not_mocked() throws Throwable {
assertThat(new A("random string").check(), equalTo("checked random string"));
}
@Test
public void test_mocked() throws Throwable {
A a = mock(A.class);
when(a.check()).thenReturn("test");
PowerMockito.whenNew(A.class).withArguments(Mockito.anyString()).thenReturn(a);
assertThat(new A("random string").check(), equalTo("test"));
}
}
Both tests should pass with mockito 1.9.0, powermockito 1.4.12 and junit 4.8.2
From a pipe
# This Is a cat
'This', 'Is', 'a', 'cat' | & {"$input"}
# This-Is-a-cat
'This', 'Is', 'a', 'cat' | & {$ofs='-';"$input"}
Write-Host
# This Is a cat
Write-Host 'This', 'Is', 'a', 'cat'
# This-Is-a-cat
Write-Host -Separator '-' 'This', 'Is', 'a', 'cat'
If your onclick function returns false the default browser behaviour is cancelled. As such:
<a href='http://www.google.com' onclick='return check()'>check</a>
<script type='text/javascript'>
function check()
{
return false;
}
</script>
Either way, whether google does it or not isn't of much importance. It's cleaner to bind your onclick functions within javascript - this way you separate your HTML from other code.
1st way is to use props
<Row id = "someRandomID">
Wherein, in the Definition, you may just go
const Row = props => {
div id = {props.id}
}
The same could be done with class, replacing id with className in the above example.
You might as well use react-html-id
, that is an npm package.
This is an npm package that allows you to use unique html IDs for components without any dependencies on other libraries.
Ref: react-html-id
Peace.
In simple words View is the UI element which we interact with when we use an app,like button,edit text and image etc.View is the child class of Android.view.View While View group is the container which contains all these views inside it in addition to several othe viewgroups like linear or Frame Layout etc. Example if we design & take the root element as Linear layout now our main layout is linear layout inside it we can take another view group (i.e another Linear layout) & many other views like buttons or textview etc.
Old Answer (July 2016):
You can't directly debug Chrome for iOS due to restrictions on the published WKWebView
apps, but there are a few options already discussed in other SO threads:
If you can reproduce the issue in Safari as well, then use Remote Debugging with Safari Web Inspector. This would be the easiest approach.
WeInRe allows some simple debugging, using a simple client-server model. It's not fully featured, but it may well be enough for your problem. See instructions on set up here.
You could try and create a simple WKWebView
browser app (some instructions here), or look for an existing one on GitHub. Since Chrome uses the same rendering engine, you could debug using that, as it will be close to what Chrome produces.
There's a "bug" opened up for WebKit: Allow Web Inspector usage for release builds of WKWebView. If and when we get an API to WKWebView
, Chrome for iOS would be debuggable.
Update January 2018:
Since my answer back in 2016, some work has been done to improve things.
There is a recent project called RemoteDebug iOS WebKit Adapter, by some of the Microsoft team. It's an adapter that handles the API differences between Webkit Remote Debugging Protocol and Chrome Debugging Protocol, and this allows you to debug iOS WebViews in any app that supports the protocol - Chrome DevTools, VS Code etc.
Check out the getting started guide in the repo, which is quite detailed.
If you are interesting, you can read up on the background and architecture here.
I created a DefaultableDictionary to do exactly what you are asking for!
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace DefaultableDictionary {
public class DefaultableDictionary<TKey, TValue> : IDictionary<TKey, TValue> {
private readonly IDictionary<TKey, TValue> dictionary;
private readonly TValue defaultValue;
public DefaultableDictionary(IDictionary<TKey, TValue> dictionary, TValue defaultValue) {
this.dictionary = dictionary;
this.defaultValue = defaultValue;
}
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() {
return dictionary.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator() {
return GetEnumerator();
}
public void Add(KeyValuePair<TKey, TValue> item) {
dictionary.Add(item);
}
public void Clear() {
dictionary.Clear();
}
public bool Contains(KeyValuePair<TKey, TValue> item) {
return dictionary.Contains(item);
}
public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex) {
dictionary.CopyTo(array, arrayIndex);
}
public bool Remove(KeyValuePair<TKey, TValue> item) {
return dictionary.Remove(item);
}
public int Count {
get { return dictionary.Count; }
}
public bool IsReadOnly {
get { return dictionary.IsReadOnly; }
}
public bool ContainsKey(TKey key) {
return dictionary.ContainsKey(key);
}
public void Add(TKey key, TValue value) {
dictionary.Add(key, value);
}
public bool Remove(TKey key) {
return dictionary.Remove(key);
}
public bool TryGetValue(TKey key, out TValue value) {
if (!dictionary.TryGetValue(key, out value)) {
value = defaultValue;
}
return true;
}
public TValue this[TKey key] {
get
{
try
{
return dictionary[key];
} catch (KeyNotFoundException) {
return defaultValue;
}
}
set { dictionary[key] = value; }
}
public ICollection<TKey> Keys {
get { return dictionary.Keys; }
}
public ICollection<TValue> Values {
get
{
var values = new List<TValue>(dictionary.Values) {
defaultValue
};
return values;
}
}
}
public static class DefaultableDictionaryExtensions {
public static IDictionary<TKey, TValue> WithDefaultValue<TValue, TKey>(this IDictionary<TKey, TValue> dictionary, TValue defaultValue ) {
return new DefaultableDictionary<TKey, TValue>(dictionary, defaultValue);
}
}
}
This project is a simple decorator for an IDictionary object and an extension method to make it easy to use.
The DefaultableDictionary will allow for creating a wrapper around a dictionary that provides a default value when trying to access a key that does not exist or enumerating through all the values in an IDictionary.
Example: var dictionary = new Dictionary<string, int>().WithDefaultValue(5);
Blog post on the usage as well.
You can use .empty()
, like this:
$("#foo").empty();
Remove all child nodes of the set of matched elements from the DOM.
This might not be the most useful answer, more of an addendum, but the above answer (from greenkode) confused me for all of 10 seconds.
"Add Folder" only lets you see folders that are the sub-folders of the project whose build path you are looking at.
The "Link Source" button in the above image would be called "Add External Folder" in an ideal world.
I had to make a properties file that is to be shared between multiple projects, and by keeping the properties file in an external folder, I am able to have only one, instead of having a copy in each project.
package com.adil.util;
/**
* The Class RandomColor.
*
* @author Adil OUIDAD
* @URL : http://kizana.fr
*/
public class RandomColor {
/**
* Gets the random color.
*
* @return the random color
*/
public static String getRandomColor() {
String[] letters = {"0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"};
String color = "#";
for (int i = 0; i < 6; i++ ) {
color += letters[(int) Math.round(Math.random() * 15)];
}
return color;
}
}
I believe the easiest way is to upload the file using MYSQL command line.
using the command from the terminal to access MySQL command line and run source
mysql --host=hostname -uuser -ppassword
source filename.sql
or directly from the terminal
mysql --host=hostname -uuser -ppassword < filename.sql
at the prompt
I found this link How to upload big sql dump files (memory, HTTP or timeout problems) in MYSQL. it give the outline of what to do to upload a large SQL. It helped me when I got face with a client 196mb sql dump. Something the PHPMySql couldn't handle.
Moment.js stores dates it utc and can apply different timezones to it. By default it applies your local timezone. If you want to set time on utc date time you need to specify utc timezone.
Try the following code:
var m = moment().utcOffset(0);
m.set({hour:0,minute:0,second:0,millisecond:0})
m.toISOString()
m.format()
I made it...
I just write
jQuery('#container').append(html)
instead
document.getElementById('container').innerHTML += html;
FWIW, htpasswd -n username
will output the result directly to stdout, and avoid touching files altogether.
It works for me when I define the complete border
property. (JSFiddle here)
.field_set{
border: 1px #F00 solid;
}?
the reason is the border-style
that is set to none
by default for fieldsets. You need to override that as well.
var id = $(this).find('option:selected').attr('id');
then you do whatever you want with selectedIndex
I've reedited my answer ... since selectedIndex isn't a good variable to give example...
I was looking for a different problem and came across this, so I will add my solution to a related problem: comparing two Maps.
// make a copy of the data
Map<String,String> a = new HashMap<String,String>(actual);
Map<String,String> e = new HashMap<String,String>(expected);
// check *every* expected value
for(Map.Entry<String, String> val : e.entrySet()){
// check for presence
if(!a.containsKey(val.getKey())){
System.out.println(String.format("Did not find expected value: %s", val.getKey()));
}
// check for equality
else{
if(0 != a.get(val.getKey()).compareTo(val.getValue())){
System.out.println(String.format("Value does not match expected: %s", val.getValue()));
}
// we have found the item, so remove it
// from future consideration. While it
// doesn't affect Java Maps, other types of sets
// may contain duplicates, this will flag those
// duplicates.
a.remove(val.getKey());
}
}
// check to see that we did not receive extra values
for(Map.Entry<String,String> val : a.entrySet()){
System.out.println(String.format("Found unexpected value: %s", val.getKey()));
}
It works on the same principle as the other solutions but also compares not only that values are present, but that they contain the same value. Mostly I've used this in accounting software when comparing data from two sources (Employee and Manager entered values match; Customer and Corporate transactions match; ... etc)
The following steps work for a fresh install of postgres 9.1 on Ubuntu 12.04. (Worked for postgres 9.3.9 on Ubuntu 14.04 too.)
By default, postgres creates a user named 'postgres'. We log in as her, and give her a password.
$ sudo -u postgres psql
\password
Enter password: ...
...
Logout of psql
by typing \q
or ctrl+d
. Then we connect as 'postgres'. The -h localhost
part is important: it tells the psql
client that we wish to connect using a TCP connection (which is configured to use password authentication), and not by a PEER connection (which does not care about the password).
$ psql -U postgres -h localhost
In C and in C++ single quotes identify a single character, while double quotes create a string literal. 'a'
is a single a character literal, while "a"
is a string literal containing an 'a'
and a null terminator (that is a 2 char array).
In C++ the type of a character literal is char
, but note that in C, the type of a character literal is int
, that is sizeof 'a'
is 4 in an architecture where ints are 32bit (and CHAR_BIT is 8), while sizeof(char)
is 1 everywhere.
use c methods
FILE *fp =fopen("filename","mode");
fclose(fp);
mode means a for appending r for reading ,w for writing
/ / using ofstream constructors.
#include <iostream>
#include <fstream>
std::string input="some text to write"
std::ofstream outfile ("test.txt");
outfile <<input << std::endl;
outfile.close();
You can use an ArrayList
and then use the toArray()
method. But depending on what you are doing, you might not even need an array at all. Look into seeing if Lists
are more what you want.
See: Java List Tutorial
n = 2
[list(x) for x in mit.divide(n, range(5, 11))]
# [[5, 6, 7], [8, 9, 10]]
[list(x) for x in mit.divide(n, range(5, 12))]
# [[5, 6, 7, 8], [9, 10, 11]]
Install via > pip install more_itertools
.
"Map<String , String > map = new HapshMap<String , String>;
map.add("one","java");
map.add("two" ,"spring");
Set<Entry<String,String>> set = map.entrySet();
List<Entry<String , String>> list = new ArrayList<Entry<String , String>> (set);
for(Entry<String , String> entry : list ) {
System.out.println(entry.getKey());
System.out.println(entry.getValue());
} "
Apple provides detailed, illustrated instructions covering every step of the process. Log in to the iPhone developer site and click the "program portal" link. In the program portal you'll find a link to the program portal user's guide, which is a really good reference and guide on this topic.
Copy the bin file path you installed
YOUR PATH
open terminal and edit environment file by typing following command,
sudo nano /etc/environment
In this file, add the following line (replacing YOUR_PATH
by the just copied path):
JAVA_HOME="YOUR_PATH"
That should be enough to set the environment variable. Now reload this file:
source /etc/environment
now test it by executing:
echo $JAVA_HOME
you can use pixels or percent.
<div id="container">
<img id="image" src="...">
</div>
css
#image
{
width:100%;
height:
}
Slightly modified (bastardized?) version of the answer by Tod Thomson as a static function rather than a separate class (I wanted to be able to call it in a WebForm viewbinding from a viewutils class I already had included).
public static bool isDebugging() {
bool debugging = false;
WellAreWe(ref debugging);
return debugging;
}
[Conditional("DEBUG")]
private static void WellAreWe(ref bool debugging)
{
debugging = true;
}
SET STATISTICS TIME ON
SELECT *
FROM Production.ProductCostHistory
WHERE StandardCost < 500.00;
SET STATISTICS TIME OFF;
And see the message tab it will look like this:
SQL Server Execution Times:
CPU time = 0 ms, elapsed time = 10 ms.
(778 row(s) affected)
SQL Server parse and compile time:
CPU time = 0 ms, elapsed time = 0 ms.
You can use some code like this, you can adjust a height and width as per your need
protected void button_Click(object sender, EventArgs e)
{
// open a pop up window at the center of the page.
ScriptManager.RegisterStartupScript(this, typeof(string), "OPEN_WINDOW", "var Mleft = (screen.width/2)-(760/2);var Mtop = (screen.height/2)-(700/2);window.open( 'your_page.aspx', null, 'height=700,width=760,status=yes,toolbar=no,scrollbars=yes,menubar=no,location=no,top=\'+Mtop+\', left=\'+Mleft+\'' );", true);
}
INSERT INTO tab_student (name_student, id_teacher_fk)
VALUES ('dan red',
(SELECT id_teacher FROM tab_teacher WHERE name_teacher ='jason bourne')
it is advisable to store your values in lowercase to make retrieval easier and less error prone
INSERT INTO tab_teacher (name_teacher)
VALUES ('tom stills')
INSERT INTO tab_student (name_student, id_teacher_fk)
VALUES ('rich man', LAST_INSERT_ID())
Info regarding .NET / C#:
Decimal digit character: \d \d matches any decimal digit. It is equivalent to the \p{Nd} regular expression pattern, which includes the standard decimal digits 0-9 as well as the decimal digits of a number of other character sets.
If ECMAScript-compliant behavior is specified, \d is equivalent to [0-9]. For information on ECMAScript regular expressions, see the "ECMAScript Matching Behavior" section in Regular Expression Options.
My code, efficient without tables or additional variables:
SELECT
((SUBSTRING_INDEX(SUBSTRING_INDEX(group_concat(val order by val), ',', floor(1+((count(val)-1) / 2))), ',', -1))
+
(SUBSTRING_INDEX(SUBSTRING_INDEX(group_concat(val order by val), ',', ceiling(1+((count(val)-1) / 2))), ',', -1)))/2
as median
FROM table;
Good news, PyDrive has first class support on CoLab! PyDrive is a wrapper for the Google Drive python client. Here is an example on how you would download ALL files from a folder, similar to using glob
+ *
:
!pip install -U -q PyDrive
import os
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
from google.colab import auth
from oauth2client.client import GoogleCredentials
# 1. Authenticate and create the PyDrive client.
auth.authenticate_user()
gauth = GoogleAuth()
gauth.credentials = GoogleCredentials.get_application_default()
drive = GoogleDrive(gauth)
# choose a local (colab) directory to store the data.
local_download_path = os.path.expanduser('~/data')
try:
os.makedirs(local_download_path)
except: pass
# 2. Auto-iterate using the query syntax
# https://developers.google.com/drive/v2/web/search-parameters
file_list = drive.ListFile(
{'q': "'1SooKSw8M4ACbznKjnNrYvJ5wxuqJ-YCk' in parents"}).GetList()
for f in file_list:
# 3. Create & download by id.
print('title: %s, id: %s' % (f['title'], f['id']))
fname = os.path.join(local_download_path, f['title'])
print('downloading to {}'.format(fname))
f_ = drive.CreateFile({'id': f['id']})
f_.GetContentFile(fname)
with open(fname, 'r') as f:
print(f.read())
Notice that the arguments to drive.ListFile
is a dictionary that coincides with the parameters used by Google Drive HTTP API (you can customize the q
parameter to be tuned to your use-case).
Know that in all cases, files/folders are encoded by id's (peep the 1SooKSw8M4ACbznKjnNrYvJ5wxuqJ-YCk) on Google Drive. This requires that you search Google Drive for the specific id corresponding to the folder you want to root your search in.
For example, navigate to the folder "/projects/my_project/my_data"
that
is located in your Google Drive.
See that it contains some files, in which we want to download to CoLab. To get the id of the folder in order to use it by PyDrive, look at the url and extract the id parameter. In this case, the url corresponding to the folder was:
Where the id is the last piece of the url: 1SooKSw8M4ACbznKjnNrYvJ5wxuqJ-YCk.
you have to iterate gridview Rows
for (int count = 0; count < grd.Rows.Count; count++)
{
if (((CheckBox)grd.Rows[count].FindControl("yourCheckboxID")).Checked)
{
((Label)grd.Rows[count].FindControl("labelID")).Text
}
}
Just use the following code with initializing a field
private int count = 0;
@Override
public void onBackPressed() {
count++;
if (count >=1) {
/* If count is greater than 1 ,you can either move to the next
activity or just quit. */
Intent intent = new Intent(this, SecondActivity.class);
startActivity(intent);
finish();
overridePendingTransition
(R.anim.push_left_in, R.anim.push_left_out);
/* Quitting */
finishAffinity();
} else {
Toast.makeText(this, "Press back again to Leave!", Toast.LENGTH_SHORT).show();
// resetting the counter in 2s
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
count = 0;
}
}, 2000);
}
super.onBackPressed();
}
As mentionned here, I've made it work with some ":before" pseudo-class and a small bit of javascript. Here is the idea :
#myInput:before{ content:"Date of birth"; width:100%; color:#AAA; }
#myInput:focus:before,
#myInput.not_empty:before{ content:none }
Then in javascript, add the "not_empty" class depending on the value in the onChange and onKeyUp events.
You can even add all of this dynamically on every date fields. Check my answer on the other thread for the code.
It's not perfect but it's working well in Chrome and iOS7 webviews. Maybe it could help you.
I think what you want is:
select {
direction: rtl;
}
fiddled here: http://jsfiddle.net/neilheinrich/XS3yQ/
I know this post is ancient but, I found it useful.
It didn't resolve my issue of returning the record with a non empty text field so I thought I would add my solution.
This is the where clause that worked for me.
WHERE xyz LIKE CAST('% %' as text)
In order to make it work you need to convert key from str to tuple before decryption(ast.literal_eval function). Here is fixed code:
import Crypto
from Crypto.PublicKey import RSA
from Crypto import Random
import ast
random_generator = Random.new().read
key = RSA.generate(1024, random_generator) #generate pub and priv key
publickey = key.publickey() # pub key export for exchange
encrypted = publickey.encrypt('encrypt this message', 32)
#message to encrypt is in the above line 'encrypt this message'
print 'encrypted message:', encrypted #ciphertext
f = open ('encryption.txt', 'w')
f.write(str(encrypted)) #write ciphertext to file
f.close()
#decrypted code below
f = open('encryption.txt', 'r')
message = f.read()
decrypted = key.decrypt(ast.literal_eval(str(encrypted)))
print 'decrypted', decrypted
f = open ('encryption.txt', 'w')
f.write(str(message))
f.write(str(decrypted))
f.close()
You need to either provide the absolute path to data.csv, or run your script in the same directory as data.csv.
I found the Invalidate() creating too much of flickering. Here's my situation. A custom control I am developing draws its whole contents via handling the Paint event.
this.Paint += this.OnPaint;
This handler calls a custom routine that does the actual painting.
private void OnPaint(object sender, PaintEventArgs e)
{
this.DrawFrame(e.Graphics);
}
To simulate scrolling I want to repaint my control every time the cursor moves while the left mouse button is pressed. My first choice was using the Invalidate() like the following.
private void RedrawFrame()
{
var r = new Rectangle(
0, 0, this.Width, this.Height);
this.Invalidate(r);
this.Update();
}
The control scrolls OK but flickers far beyond any comfortable level. So I decided, instead of repainting the control, to call my custom DrawFrame() method directly after handling the MouseMove event. That produced a smooth scrolling with no flickering.
private void RedrawFrame()
{
var g = Graphics.FromHwnd(this.Handle);
this.DrawFrame(g);
}
This approach may not be applicable to all situations, but so far it suits me well.
Use varchar instead of VAR_CHAR and omit the comma in the last line i.e.phone INT NOT NULL );. The last line during creating table is kept "comma free". Ex:- CREATE TABLE COMPUTER ( Model varchar(50) ); Here, since we have only one column ,that's why there is no comma used during entire code.
If you would like to show it in a new window, you could use Tkinter + PIL library, like so:
import tkinter as tk
from PIL import ImageTk, Image
def show_imge(path):
image_window = tk.Tk()
img = ImageTk.PhotoImage(Image.open(path))
panel = tk.Label(image_window, image=img)
panel.pack(side="bottom", fill="both", expand="yes")
image_window.mainloop()
This is a modified example that can be found all over the web.
In 12c, here's the new way:
select bla
from bla
where bla
order by finaldate desc
fetch first 1 rows only;
How nice is that!
one way is if you have a jdk installed , in bin folder there is a utility called jconsole(even visualvm can be used). Launch it and connect to the relevant java process and you can see what are the heap size settings set and many other details
When running headless or cli only, jConsole can be used over lan, if you specify a port to connect on when starting the service in question.
As json.loads
simply returns a dict, you can use the operators that apply to dicts:
>>> jdata = json.load('{"uri": "http:", "foo", "bar"}')
>>> 'uri' in jdata # Check if 'uri' is in jdata's keys
True
>>> jdata['uri'] # Will return the value belonging to the key 'uri'
u'http:'
Edit: to give an idea regarding how to loop through the data, consider the following example:
>>> import json
>>> jdata = json.loads(open ('bookmarks.json').read())
>>> for c in jdata['children'][0]['children']:
... print 'Title: {}, URI: {}'.format(c.get('title', 'No title'),
c.get('uri', 'No uri'))
...
Title: Recently Bookmarked, URI: place:folder=BOOKMARKS_MENU(...)
Title: Recent Tags, URI: place:sort=14&type=6&maxResults=10&queryType=1
Title: , URI: No uri
Title: Mozilla Firefox, URI: No uri
Inspecting the jdata
data structure will allow you to navigate it as you wish. The pprint
call you already have is a good starting point for this.
Edit2: Another attempt. This gets the file you mentioned in a list of dictionaries. With this, I think you should be able to adapt it to your needs.
>>> def build_structure(data, d=[]):
... if 'children' in data:
... for c in data['children']:
... d.append({'title': c.get('title', 'No title'),
... 'uri': c.get('uri', None)})
... build_structure(c, d)
... return d
...
>>> pprint.pprint(build_structure(jdata))
[{'title': u'Bookmarks Menu', 'uri': None},
{'title': u'Recently Bookmarked',
'uri': u'place:folder=BOOKMARKS_MENU&folder=UNFILED_BOOKMARKS&(...)'},
{'title': u'Recent Tags',
'uri': u'place:sort=14&type=6&maxResults=10&queryType=1'},
{'title': u'', 'uri': None},
{'title': u'Mozilla Firefox', 'uri': None},
{'title': u'Help and Tutorials',
'uri': u'http://www.mozilla.com/en-US/firefox/help/'},
(...)
}]
To then "search through it for u'uri': u'http:'
", do something like this:
for c in build_structure(jdata):
if c['uri'].startswith('http:'):
print 'Started with http'
If you are looking to be able to restore a table after someone has mistakenly deleted rows from it you could maybe have a look at database snapshots. You could restore the table quite easily (or a subset of the rows) from the snapshot. See http://msdn.microsoft.com/en-us/library/ms175158.aspx
For me TransactionTooLargeException occurred when i tried to send large bitmap image from one activity to another via intent. I solved this problem by using Application's Global Variables.
For example if you want to send large bitmap image from an activity A to to activity B, then store that bitmap image in global variable
((Global) this.getApplication()).setBitmap(bitmap);
then start activity B and read from global variable
Bitmap bitmap = ((Global) this.getApplication()).getBitmap();
Use an html button and javascript? in javascript, window.location
is used to change the url location of the current window, while window.open
will open a new one
<input type="button" onclick="window.open('newPage.aspx', 'newPage');" />
Edit: Ah, just found this: If the ID of your form tag is form1
, set this attribute in your asp button
OnClientClick="form1.target ='_blank';"
->
calls/sets object variables. Ex:
$obj = new StdClass;
$obj->foo = 'bar';
var_dump($obj);
=> Sets key/value pairs for arrays. Ex:
$array = array(
'foo' => 'bar'
);
var_dump($array);
Changing only what's after hash - old browsers
document.location.hash = 'lookAtMeNow';
Changing full URL. Chrome, Firefox, IE10+
history.pushState('data to be passed', 'Title of the page', '/test');
The above will add a new entry to the history so you can press Back button to go to the previous state. To change the URL in place without adding a new entry to history use
history.replaceState('data to be passed', 'Title of the page', '/test');
Try running these in the console now!
Simpler with the aggregate function string_agg()
(Postgres 9.0 or later):
SELECT movie, string_agg(actor, ', ') AS actor_list
FROM tbl
GROUP BY 1;
The 1
in GROUP BY 1
is a positional reference and a shortcut for GROUP BY movie
in this case.
string_agg()
expects data type text
as input. Other types need to be cast explicitly (actor::text
) - unless an implicit cast to text
is defined - which is the case for all other character types (varchar
, character
, "char"
), and some other types.
As isapir commented, you can add an ORDER BY
clause in the aggregate call to get a sorted list - should you need that. Like:
SELECT movie, string_agg(actor, ', ' ORDER BY actor) AS actor_list
FROM tbl
GROUP BY 1;
But it's typically faster to sort rows in a subquery. See:
This might help you guys.(I've applied this to my Projects)
Here's the 3 easy steps.
That's it. It will sync/refresh your Model base on the changes on your database.
For detailed instructions. Please visit the link below.
EF Database First with ASP.NET MVC: Changing the Database and updating its model.
Lets assume you want a data frame with the following schema:
root
|-- k: string (nullable = true)
|-- v: integer (nullable = false)
You simply define schema for a data frame and use empty RDD[Row]
:
import org.apache.spark.sql.types.{
StructType, StructField, StringType, IntegerType}
import org.apache.spark.sql.Row
val schema = StructType(
StructField("k", StringType, true) ::
StructField("v", IntegerType, false) :: Nil)
// Spark < 2.0
// sqlContext.createDataFrame(sc.emptyRDD[Row], schema)
spark.createDataFrame(sc.emptyRDD[Row], schema)
PySpark equivalent is almost identical:
from pyspark.sql.types import StructType, StructField, IntegerType, StringType
schema = StructType([
StructField("k", StringType(), True), StructField("v", IntegerType(), False)
])
# or df = sc.parallelize([]).toDF(schema)
# Spark < 2.0
# sqlContext.createDataFrame([], schema)
df = spark.createDataFrame([], schema)
Using implicit encoders (Scala only) with Product
types like Tuple
:
import spark.implicits._
Seq.empty[(String, Int)].toDF("k", "v")
or case class:
case class KV(k: String, v: Int)
Seq.empty[KV].toDF
or
spark.emptyDataset[KV].toDF
<div id"content">
<div id"contentLeft"></div>
<div id"contentRight"></div>
</div>
#content {
clear: both;
width: 950px;
padding-bottom: 10px;
background:#fff;
overflow:hidden;
}
#contentLeft {
float: left;
display:inline;
width: 630px;
margin: 10px;
background:#fff;
}
#contentRight {
float: right;
width: 270px;
margin-top:25px;
margin-right:15px;
background:#d7e5f7;
}
Obviously you will need to adjust the size of the columns to suit your site as well as colours etc but that should do it. You also need to make sure that your ContentLeft and ContentRight widths do not exceed the Contents width (including margins).
The code for specific digits after decimals is:
var a = 1.543240952039
var roundedString = String(format: "%.3f", a)
Here the %.3f tells the swift to make this number rounded to 3 decimal places.and if you want double number, you may use this code:
// String to Double
var roundedString = Double(String(format: "%.3f", b))
DataGridView.Refresh
and And DataGridView.Update
are methods that are inherited from Control. They have to do with redrawing the control which is why new rows don't appear.
My guess is the data retrieval is on the Form_Load. If you want your Button on Form B to retrieve the latest data from the database then that's what you have to do whatever Form_Load is doing.
A nice way to do that is to separate your data retrieval calls into a separate function and call it from both the From Load and Button Click events.
If the dataframes DO NOT all have the same columns try the following:
df = pd.DataFrame.from_dict(map(dict,df_list))
Since -f
caused another problem, I developed another solution.
The -f
flag does not solved my problem because my onbuild
image looks for a file in a folder and had to call like this:
-f foo/bar/Dockerfile foo/bar
instead of
-f foo/bar/Dockerfile .
Also note that this is only solution for some cases as -f
flag
The git package installed on your system includes bash files to aid you in creating an informative prompt. To create colors, you will need to insert terminal escape sequences into your prompt. And, the final ingredient is to update your prompt after each command gets executed by using the built-in variable PROMPT_COMMAND.
Edit your ~/.bashrc to include the following, and you should get the prompt in your question, modulo some color differences.
#
# Git provides a bash file to create an informative prompt. This is its standard
# location on Linux. On Mac, you should be able to find it under your Git
# installation. If you are unable to find the file, I have a copy of it on my GitHub.
#
# https://github.com/chadversary/home/blob/42cf697ba69d4d474ca74297cdf94186430f1384/.config/kiwi-profile/40-git-prompt.sh
#
source /usr/share/git/completion/git-prompt.sh
#
# Next, we need to define some terminal escape sequences for colors. For a fuller
# list of colors, and an example how to use them, see my bash color file on my GitHub
# and my coniguration for colored man pages.
#
# https://github.com/chadversary/home/blob/42cf697ba69d4d474ca74297cdf94186430f1384/.config/kiwi-profile/10-colors.sh
# https://github.com/chadversary/home/blob/42cf697ba69d4d474ca74297cdf94186430f1384/.config/kiwi-profile/40-less.sh
#
color_start='\e['
color_end='m'
color_reset='\e[0m'
color_bg_blue='44'
#
# To get a fancy git prompt, it's not sufficient to set PS1. Instead, we set PROMPT_COMMAND,
# a built in Bash variable that gets evaluated before each render of the prompt.
#
export PROMPT_COMMAND="PS1=\"\${color_start}\${color_bg_blue}\${color_end}\u@\h [\w\$(__git_ps1 \" - %s\")]\${color_reset}\n\$ \""
#
# If you find that the working directory that appears in the prompt is ofter too long,
# then trim it.
#
export PROMPT_DIRTRIM=3
After all files have been added, the next step is a "git commit".
"git status" will suggest what to do: files yet to add are listed at the bottom, and once they are all done, it will suggest a commit at the top, where it explains the merge status of the current branch.
In my case, it was due to a broken symlink when trying to npm link a custom angular library to consuming app. After running npm link @authoring/canvas
"@authoring/canvas": "path/to/ui-authoring-canvas/dist"
It appear everything was OK but the module still couldn't be found:
When I corrected the import statement to something that the editor could find Link:
import {CirclePackComponent} from '@authoring/canvas/lib/circle-pack/circle-pack.component';
I received this which is mention in the overflow thread:
To fix this I had to:
cd /usr/local/lib/node_modules/packageName
cd ..
rm -rf packageName
a) rm -rf dist
b) npm run build
c) cd dist
d) npm link
package.json
with:"packageName": "file:/path/to/local/node_module/packageName""
Create a folder ${USER_HOME}/.mvn
and put a file called maven.config
in it.
The content should be:
-Dmaven.wagon.http.ssl.insecure=true
-Dmaven.wagon.http.ssl.allowall=true
-Dmaven.wagon.http.ssl.ignore.validity.dates=true
Hope this helps.
I initialised the slider with one of the properties as
variableWidth: true
then i could set the width of the slides to anything i wanted in CSS with:
.slick-slide {
width: 200px;
}
Finally, I got the answer.
public void onBindViewHolder(final ViewHolder holder, final int position) {
holder.tv1.setText(android_versionnames[position]);
holder.row_linearlayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
row_index=position;
notifyDataSetChanged();
}
});
if(row_index==position){
holder.row_linearlayout.setBackgroundColor(Color.parseColor("#567845"));
holder.tv1.setTextColor(Color.parseColor("#ffffff"));
}
else
{
holder.row_linearlayout.setBackgroundColor(Color.parseColor("#ffffff"));
holder.tv1.setTextColor(Color.parseColor("#000000"));
}
}
here 'row_index' is set as '-1' initially
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView tv1;
LinearLayout row_linearlayout;
RecyclerView rv2;
public ViewHolder(final View itemView) {
super(itemView);
tv1=(TextView)itemView.findViewById(R.id.txtView1);
row_linearlayout=(LinearLayout)itemView.findViewById(R.id.row_linrLayout);
rv2=(RecyclerView)itemView.findViewById(R.id.recyclerView1);
}
}
Use libcurl, here is a simple example.
EDIT: If this is about starting a web browser from C++, you can invoke a shell command with system
on a POSIX system:
system("<mybrowser> http://google.com");
By replacing <mybrowser>
with the browser you want to launch.
Just type
document.querySelector('video').playbackRate = 1.25;
in JS console of your modern browser.
Just omit the [Required] attribute from the string somefield
property. This will make it create a NULL
able column in the db.
To make int types allow NULLs in the database, they must be declared as nullable ints in the model:
// an int can never be null, so it will be created as NOT NULL in db
public int someintfield { get; set; }
// to have a nullable int, you need to declare it as an int?
// or as a System.Nullable<int>
public int? somenullableintfield { get; set; }
public System.Nullable<int> someothernullableintfield { get; set; }
Put style="float:left"
on each of your divs:
<div style="float:left;">...........
Example:
<div style="float:left;">
<label for="username">First Name</label>
<input id="user_first_name" name="user[first_name]" size="30" type="text" />
</div>
<div style="float:left;">
<label for="name">Last Name</label>
<input id="user_last_name" name="user[last_name]" size="30" type="text" />
</div>
To put an element on new line, put this div below it:
<div style="clear:both;"> </div>
Of course, you can also create classes in the CSS file:
.left{
float:left;
}
.clear{
clear:both;
}
And then your html should look like this:
<div class="left">
<label for="username">First Name</label>
<input id="user_first_name" name="user[first_name]" size="30" type="text" />
</div>
<div class="left">
<label for="name">Last Name</label>
<input id="user_last_name" name="user[last_name]" size="30" type="text" />
</div>
To put an element on new line, put this div below it:
<div class="clear"> </div>
More Info:
In case anybody is here and the other two solutions do not make the trick, check that what you are using to filter is what you expect:
user = UniversityDetails.objects.get(email=email)
is email a str
, or a None
? or an int
?
Did you try vertical-align: middle ???
You can find more info on vertical-align here: http://www.w3schools.com/css/pr_pos_vertical-align.asp
If you want SSMS to maintain a query history, use the SSMS Tool Pack add on.
If you want to monitor the SQL Server for currently running queries, use SQL PRofiler as other have already suggested.
Simply in windows
ctrl + @ (the button 2 in the upper horizontal row of numbers in keyboard)
I had a problem with accented characters when converting a PHP array to JSON. I put UTF-8 stuff all over the place but nothing solved my problem until I added this piece of code in my PHP while loop where I was pushing the array:
$es_words[] = array(utf8_encode("$word"),"$alpha","$audio");
It was only the '$word' variable that was giving a problem. Afterwards it did a jason_encode no problem.
Hope that helps
ps -eo pid,cmd,lstart | grep YOUR-PID-HERE
More recent and much cleaner: use event.key
. No more arbitrary number codes!
NOTE: The old properties (
.keyCode
and.which
) are Deprecated.
node.addEventListener('keydown', function(event) {
const key = event.key; // "a", "1", "Shift", etc.
});
If you want to make sure only single characters are entered, check key.length === 1
, or that it is one of the characters you expect.
I like to use gitk name_of_file
This shows a nice list of the changes that happened to a file at each commit, instead of showing the changes to all the files. Makes it easier to track down something that happened.
None of the above, if you are on a Mac. Use Charles Proxy. It's the best network/request information collecter that I have ever come across. You can view and edit all outgoing requests, and see the responses from those requests in several forms, depending on the type of the response. It costs 50 dollars for a license, but you can download the trial version and see what you think.
If your on Windows, then I would just stay with Fiddler.
I modified vartec's answer a bit since I needed to get the error codes from the function. (Thanks vertec!!! its an awesome trick)
This can also be done with a manager.list
but I think is better to have it in a dict and store a list within it. That way, way we keep the function and the results since we can't be sure of the order in which the list will be populated.
from multiprocessing import Process
import time
import datetime
import multiprocessing
def func1(fn, m_list):
print 'func1: starting'
time.sleep(1)
m_list[fn] = "this is the first function"
print 'func1: finishing'
# return "func1" # no need for return since Multiprocess doesnt return it =(
def func2(fn, m_list):
print 'func2: starting'
time.sleep(3)
m_list[fn] = "this is function 2"
print 'func2: finishing'
# return "func2"
def func3(fn, m_list):
print 'func3: starting'
time.sleep(9)
# if fail wont join the rest because it never populate the dict
# or do a try/except to get something in return.
raise ValueError("failed here")
# if we want to get the error in the manager dict we can catch the error
try:
raise ValueError("failed here")
m_list[fn] = "this is third"
except:
m_list[fn] = "this is third and it fail horrible"
# print 'func3: finishing'
# return "func3"
def runInParallel(*fns): # * is to accept any input in list
start_time = datetime.datetime.now()
proc = []
manager = multiprocessing.Manager()
m_list = manager.dict()
for fn in fns:
# print fn
# print dir(fn)
p = Process(target=fn, name=fn.func_name, args=(fn, m_list))
p.start()
proc.append(p)
for p in proc:
p.join() # 5 is the time out
print datetime.datetime.now() - start_time
return m_list, proc
if __name__ == '__main__':
manager, proc = runInParallel(func1, func2, func3)
# print dir(proc[0])
# print proc[0]._name
# print proc[0].name
# print proc[0].exitcode
# here you can check what did fail
for i in proc:
print i.name, i.exitcode # name was set up in the Process line 53
# here will only show the function that worked and where able to populate the
# manager dict
for i, j in manager.items():
print dir(i) # things you can do to the function
print i, j
Object destructuring the parameter object is what many of the answers above are aiming for and Typescript now has the methods in place to make it much easier to read and intuitively understand.
Destructuring Basics: By destructuring an object, you can choose properties from an object by key name. You can define as few or as many of the properties you like, and default values are set by a basic syntax of let {key = default} = object
.
let {firstName, lastName = 'Smith'} = myParamsObject;
//Compiles to:
var firstName = myParamsObject.firstName,
_a = myParamsObject.lastName,
lastName = _a === void 0 ? 'Smith' : _a;
Writing an interface, type or class for the parameter object improves legibility.
type FullName = {_x000D_
firstName: string;_x000D_
_x000D_
/** @default 'Smith' */_x000D_
lastName ? : string;_x000D_
}_x000D_
_x000D_
function sayName(params: FullName) {_x000D_
_x000D_
// Set defaults for parameter object_x000D_
var { firstName, lastName = 'Smith'} = params;_x000D_
_x000D_
// Do Stuff_x000D_
var name = firstName + " " + lastName;_x000D_
alert(name);_x000D_
}_x000D_
_x000D_
// Use it_x000D_
sayName({_x000D_
firstName: 'Bob'_x000D_
});
_x000D_
If you do not what to use the standard notation you can also create/simulate it using infix with something like this:
create a class to hold your target and result:
data class Ternary<T>(val target: T, val result: Boolean)
create some infix functions to simulate a ternary operation
infix fun <T> Boolean.then(target: T): Ternary<T> {
return Ternary(target, this)
}
infix fun <T> Ternary<T>.or(target: T): T {
return if (this.result) this.target else target
}
Then you will be able to use it like this:
val collection: List<Int> = mutableListOf(1, 2, 3, 4)
var exampleOne = collection.isEmpty() then "yes" or "no"
var exampleTwo = (collection.isNotEmpty() && collection.contains(2)) then "yes" or "no"
var exampleThree = collection.contains(1) then "yes" or "no"
it means pointer you can use this link to get more info about pointer http://www.cprogramming.com/tutorial/c/lesson6.html
it can only be lazily loaded whilst within a transaction. So you could access the collection in your repository, which has a transaction - or what I normally do is a get with association
, or set fetchmode to eager.
Another method in one line (substitute your actual path/ports if needed).
Example: Assume a generic registry:2.0 start up, the running registry container has a log file that holds images and tag names. I extrapolate the data like this:
grep -r -o "vars\.name=.* vars.reference=.*" /var/lib/docker/containers/* | cut -c 167-225 | sed 's/ver.*$//' | sed 's/vars\.name=//' | sed 's/ vars\.reference=/:/' | sort -u
You may need to tweak the cut values to get the output desired.
To answer the question in a general manner:
Using z-index
will allow you to control this. see z-index at csstricks.
The element of higher z-index
will be displayed on top of elements of lower z-index
.
For instance, take the following HTML:
<div id="first">first</div>
<div id="second">second</div>
If I have the following CSS:
#first {
position: fixed;
z-index: 2;
}
#second {
position: fixed;
z-index: 1;
}
#first
wil be on top of #second
.
But specifically in your case:
The div
element is a child of the div
that you wish to put in front. This is not logically possible.
The efficient way to do that is just to cast to a generic Map as follows:
Properties props = new Properties();
Map<String, String> map = (Map)props;
This will convert a Map<Object, Object>
to a raw Map, which is "ok" for the compiler (only warning). Once we have a raw Map
it will cast to Map<String, String>
which it also will be "ok" (another warning). You can ignore them with annotation @SuppressWarnings({ "unchecked", "rawtypes" })
This will work because in the JVM the object doesn't really have a generic type. Generic types are just a trick that verifies things at compile time.
If some key or value is not a String it will produce a ClassCastException
error. With current Properties
implementation this is very unlikely to happen, as long as you don't use the mutable call methods from the super Hashtable<Object,Object>
of Properties
.
So, if don't do nasty things with your Properties instance this is the way to go.
You can simply do:
Serial.println(n);
which will convert n
to an ASCII string automatically. See the documentation for Serial.println()
.
You're swapping endianness between your two methods. You have intToByteArray(int a)
assigning the low-order bits into ret[0]
, but then byteArrayToInt(byte[] b)
assigns b[0]
to the high-order bits of the result. You need to invert one or the other, like:
public static byte[] intToByteArray(int a)
{
byte[] ret = new byte[4];
ret[3] = (byte) (a & 0xFF);
ret[2] = (byte) ((a >> 8) & 0xFF);
ret[1] = (byte) ((a >> 16) & 0xFF);
ret[0] = (byte) ((a >> 24) & 0xFF);
return ret;
}
Try This
SELECT @PrimaryContactKey = c.PrimaryCntctKey
FROM tarcustomer c, tarinvoice i
WHERE i.custkey = c.custkey
AND i.invckey = @tmp_key
UPDATE tarinvoice SET confirmtocntctkey = @PrimaryContactKey
WHERE invckey = @tmp_key
FETCH NEXT FROM @get_invckey INTO @tmp_key
You would declare this variable outside of your loop as just a standard TSQL variable.
I should also note that this is how you would do it for any type of select into a variable, not just when dealing with cursors.
I do not know. A lot of places do not do unit test, but the quality of the code is good. Microsoft does unit test, but Bill Gates gave a blue screen at his presentation.
When you have three columns : first_name, last_name, mid_name:
SELECT CASE
WHEN mid_name IS NULL OR TRIM(mid_name) ='' THEN
CONCAT_WS( " ", first_name, last_name )
ELSE
CONCAT_WS( " ", first_name, mid_name, last_name )
END
FROM USER;
sudo apt-get --purge remove node
sudo apt-get --purge remove nodejs-legacy
sudo apt-get --purge remove nodejs
sudo apt-get install nodejs-legacy
source ~/.profile
Combined the accepted answer with source ~/.profile
from the comment that has been folded and some clean up commands before. Most likely you will also need to sudo apt-get install npm
after.
Just an update:
You should use ::ng-deep
instead of /deep/
which seems to be deprecated.
Per documentation:
The shadow-piercing descendant combinator is deprecated and support is being removed from major browsers and tools. As such we plan to drop support in Angular (for all 3 of /deep/, >>> and ::ng-deep). Until then ::ng-deep should be preferred for a broader compatibility with the tools.
You can find it here
Maybe you are looking for Vector
. It's capacity is automatically expanded if needed. It's not the best choice but will do in simple situations. It's worth your time to read up on ArrayList
instead.
Let me add an example here:
I'm trying to build Alluxio
on windows platform and got the same issue, it's because the pom.xml
contains below step:
<plugin>
<artifactId>exec-maven-plugin</artifactId>
<groupId>org.codehaus.mojo</groupId>
<inherited>false</inherited>
<executions>
<execution>
<id>Check that there are no Windows line endings</id>
<phase>compile</phase>
<goals>
<goal>exec</goal>
</goals>
<configuration>
<executable>${build.path}/style/check_no_windows_line_endings.sh</executable>
</configuration>
</execution>
</executions>
</plugin>
The .sh
file is not executable on windows so the error throws.
Comment it out if you do want build Alluxio
on windows.
It turns out the answer was ridiculously simple, but mystifying as to why it was necessary.
In the IIS Manager on the server, I set the application pool for my web application to not allow 32-bit assemblies.
It seems it assumes, on a 64-bit system, that you must want the 32 bit assembly. Bizarre.
You can use Jquery's on method and listen for the scroll
event.
Even though it is little late, but PHP has one better solution for this:
$words=str_word_count($myvalue, 1);
echo $words[0];
Single LinearLayout
solution. Only adding a simple spacing view:
(No-one seemed to have mentioned this one, only more complicated multi-layout solutions.)
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="35dp">
<TextView
android:id="@+id/lblExpenseCancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/cancel"
android:textColor="#404040"
android:layout_marginLeft="10dp"
android:textSize="20sp"
android:layout_marginTop="9dp" />
<!------------------------- ADDED SPACER VIEW -------------------->
<View
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_weight="1"
/>
<!------------------------- /ADDED SPACER VIEW -------------------->
<Button
android:id="@+id/btnAddExpense"
android:layout_width="wrap_content"
android:layout_height="45dp"
android:background="@drawable/stitch_button"
android:layout_marginLeft="10dp"
android:text="@string/add"
android:layout_gravity="right"
android:layout_marginRight="15dp" />
</LinearLayout>
Note the "highlighted" View, I didn't modify anything else. Height=0 makes sure it's not visible. Width=0 is because the width is determined by the LinearLayout
based on weight=1. This means that the spacer view will stretch as much as possible in the direction (orientation) of the LinearLayout
.
Note that you should use android.widget.Space
or android.support.v4.widget.Space
instead of View
if your API level and/or dependencies allow it. Space
achieves the job in a cheaper way, because it only measures and doesn't try to draw anything like View
does; it's also more expressive conveying the intention.
Yes typically, a session will end after 20 minutes in PHP.
<input type="checkbox" name="checkAddress" onclick="if(this.checked){ alert('a'); }" />
Below are some notes which i pulled from this codeproject article on C# Out Vs Ref
If you are a visual person then please see this yourtube video which demonstrates the difference practically https://www.youtube.com/watch?v=lYdcY5zulXA
Below image shows the differences more visually
Couldn't believe that there is not one single correct answer here. No need to allocate pointers, and the unmultiplied values still need to be normalized. To cut to the chase, here is the correct version for Swift 4. For UIImage
just use .cgImage
.
extension CGImage {
func colors(at: [CGPoint]) -> [UIColor]? {
let colorSpace = CGColorSpaceCreateDeviceRGB()
let bytesPerPixel = 4
let bytesPerRow = bytesPerPixel * width
let bitsPerComponent = 8
let bitmapInfo: UInt32 = CGImageAlphaInfo.premultipliedLast.rawValue | CGBitmapInfo.byteOrder32Big.rawValue
guard let context = CGContext(data: nil, width: width, height: height, bitsPerComponent: bitsPerComponent, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: bitmapInfo),
let ptr = context.data?.assumingMemoryBound(to: UInt8.self) else {
return nil
}
context.draw(self, in: CGRect(x: 0, y: 0, width: width, height: height))
return at.map { p in
let i = bytesPerRow * Int(p.y) + bytesPerPixel * Int(p.x)
let a = CGFloat(ptr[i + 3]) / 255.0
let r = (CGFloat(ptr[i]) / a) / 255.0
let g = (CGFloat(ptr[i + 1]) / a) / 255.0
let b = (CGFloat(ptr[i + 2]) / a) / 255.0
return UIColor(red: r, green: g, blue: b, alpha: a)
}
}
}
The reason you have to draw/convert the image first into a buffer is because images can have several different formats. This step is required to convert it to a consistent format you can read.
H vs h is difference between 24 hour vs 12 hour format.
Like @Nycen I also got this error because of a link to Cloudfare. Mine was for the Select2 plugin.
to fix it I just removed
src="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.min.js"
and the error went away.
Your trouble is that you have some code that is expecting datetime
to be a reference to the datetime
module and other code that is expecting datetime
to be a reference to the datetime
class. Obviously, it can't be both.
When you do:
from datetime import datetime
import datetime
You are first setting datetime
to be a reference to the class, then immediately setting it to be a reference to the module. When you do it the other way around, it's the same thing, but it ends up being a reference to the class.
You need to rename one of these references. For example:
import datetime as dt
from datetime import datetime
Then you can change references in the form datetime.xxxx
that refer to the module to dt.xxxx
.
Or else just import datetime
and change all references to use the module name. In other words, if something just says datetime(...)
you need to change that reference to datetime.datetime
.
Python has a fair bit of this kind of thing in its library, unfortunately. If they followed their own naming guidelines in PEP 8, the datetime
class would be named Datetime
and there'd be no problem using both datetime
to mean the module and Datetime
to mean the class.
If you want to use an array, you have to keep a counter which contains the number of cars in the garage. Better use an ArrayList
instead of array:
List<Car> garage = new ArrayList<Car>();
garage.add(redCar);
I had the same issue but the password was good and "Log on as batch job" alone was not sufficient.
Check that the IIS application pool identity account or group has both the "Log on as Batch Job" permission AND that it can "impersonate a client after authentication".
To change these settings perform the following steps on the web front end server:
You should be able to access the site!
Two nitpicks. (1) Best not to use string literals for column alias - that is deprecated. (2) Just use style 120 to get the same value.
CASE
WHEN CreatedDate = '19000101' THEN ''
WHEN CreatedDate = '18000101' THEN ''
ELSE Convert(varchar(19), CreatedDate, 120)
END AS [Created Date]
You're already doing it!
save()
will check if something in the model has changed. If it hasn't it won't run a db query.
Here's the relevant part of code in Illuminate\Database\Eloquent\Model@performUpdate
:
protected function performUpdate(Builder $query, array $options = [])
{
$dirty = $this->getDirty();
if (count($dirty) > 0)
{
// runs update query
}
return true;
}
The getDirty()
method simply compares the current attributes with a copy saved in original
when the model is created. This is done in the syncOriginal()
method:
public function __construct(array $attributes = array())
{
$this->bootIfNotBooted();
$this->syncOriginal();
$this->fill($attributes);
}
public function syncOriginal()
{
$this->original = $this->attributes;
return $this;
}
If you want to check if the model is dirty just call isDirty()
:
if($product->isDirty()){
// changes have been made
}
Or if you want to check a certain attribute:
if($product->isDirty('price')){
// price has changed
}
Try another *fastcgi_param* something like
fastcgi_param SCRIPT_FILENAME /usr/share/nginx/html$fastcgi_script_name;
Try this:
function funcName() {
alert("test");
}
var run = setInterval(funcName, 10000)
Both {{ request.path }} and {{ request.get_full_path }}
return the current URL but not absolute URL, for example:
your_website.com/wallpapers/new_wallpaper
Both will return
/new_wallpaper/
(notice the leading and trailing slashes)
So you'll have to do something like
{% if request.path == '/new_wallpaper/' %}
<button>show this button only if url is new_wallpaper</button>
{% endif %}
However, you can get the absolute URL using (thanks to the answer above)
{{ request.build_absolute_uri }}
NOTE:
you don't have to include request
in settings.py
, it's already there.
<?php
// Use this function and Pass Mixed string and what you want to search in mixed string.
// For Example :
$mixedStr = "hello world. This is john duvey";
$searchStr= "john";
if(strpos($mixedStr,$searchStr)) {
echo "Your string here";
}else {
echo "String not here";
}
I don't think you need javascript or CSS to fix this.
According to the html 5 spec for buttons a button with no type attribute is treated the same as a button with its type set to "submit", i.e. as a button for submitting its containing form. Setting the button's type to "button" should prevent the behaviour you're seeing.
I'm not sure about browser support for this, but the same behaviour was specified in the html 4.01 spec for buttons so I expect it's pretty good.
I was having the same problem using my class SharedModule.
export class SharedModule {
static forRoot(): ModuleWithProviders {
return {
ngModule: SharedModule,
providers: [MyService]
}
}
}
Then I changed it putting directly in the app.modules this way
@NgModule({declarations: [
AppComponent,
NaviComponent],imports: [BrowserModule,RouterModule.forRoot(ROUTES),providers: [MoviesService],bootstrap: [MyService] })
Obs: I'm using "@angular/core": "^6.0.2".
I hope its help you.
Perhaps you try this solution:
#define QUANTIDISCHI 6
#define QUDI(x) #x
#define QUdi(x) QUDI(x)
. . .
. . .
unsigned char TheNumber[] = "QUANTIDISCHI = " QUdi(QUANTIDISCHI) "\n";
If you want to convert all elements of a
to a single numeric vector and length(a)
is greater than 1 (OK, even if it is of length 1), you could unlist
the object first and then convert.
as.numeric(unlist(a))
# [1] 10 38 66 101 129 185 283 374
Bear in mind that there aren't any quality controls here. Also, X$Days
a mighty odd name.
Query the database for an existing record with the same PK. Compare the file sizes and checksums of the new and existing images to see if they're the same.
If you want to list them all in a nice list but without using the cruddy non human friendly name, you can do this...
object.errors.each do |attr,message|
puts "<li>"+message+"</li>"
end
I had this same problem, common also to other borwsers like Firefox. Finally I discovered that dynamically create an element with animated gif inside at form submit did not animate, so I developed the following workaorund.
1) At document.ready()
, each FORM found in page, receive position:relative
property and then to each one is attached an invisible DIV.bg-overlay
.
2) After this, assuming that each submit value of my website is identified by btn-primary
css class, again at document.ready()
, I look for these buttons, traverse to the FORM parent of each one, and at form submit, I fire showOverlayOnFormExecution(this,true);
function, passing clicked button and a boolean that toggle visibility of DIV.bg-overlay
.
$(document).ready(function() {
//Append LOADING image to all forms
$('form').css('position','relative').append('<div class="bg-overlay" style="display:none;"><img src="/images/loading.gif"></div>');
//At form submit, fires a specific function
$('form .btn-primary').closest('form').submit(function (e) {
showOverlayOnFormExecution(this,true);
});
});
CSS for DIV.bg-overlay
is the following:
.bg-overlay
{
width:100%;
height:100%;
position:absolute;
top:0;
left:0;
background:rgba(255,255,255,0.6);
z-index:100;
}
.bg-overlay img
{
position:absolute;
left:50%;
top:50%;
margin-left:-40px; //my loading images is 80x80 px. This is done to center it horizontally and vertically.
margin-top:-40px;
max-width:auto;
max-height:80px;
}
3) At any form submit, the following function is fired to show a semi-white background overlay all over it (that deny ability to interact again with form) and an animated gif inside it (that visually show a loading action).
function showOverlayOnFormExecution(clicked_button, showOrNot)
{
if(showOrNot == 1)
{
//Add "content" of #bg-overlay_container (copying it) to the confrm that contains clicked button
$(clicked_button).closest('form').find('.bg-overlay').show();
}
else
$('form .bg-overlay').hide();
}
Showing animated gif at form submit, instead of appending it at this event, solves "gif animation freeze" problem of various browsers (as said, I found this problem in IE and Firefox, not in Chrome)
An alternative way you can do this, is using dictionary comprehension. This should be compatible with 2.7+
result = {
key: value for key, value in
{"foo": "bar", "lorem": None}.items()
if value
}
You listen to the onerror event by assigning a function to window.onerror:
window.onerror = function (msg, url, lineNo, columnNo, error) {
var string = msg.toLowerCase();
var substring = "script error";
if (string.indexOf(substring) > -1){
alert('Script Error: See Browser Console for Detail');
} else {
alert(msg, url, lineNo, columnNo, error);
}
return false;
};
This has been asked many times. A possible solution can be found here: https://stackoverflow.com/a/6527838/552671
This solution requires both an UPDATE
and INSERT
.
UPDATE table SET field='C', field2='Z' WHERE id=3;
INSERT INTO table (id, field, field2)
SELECT 3, 'C', 'Z'
WHERE NOT EXISTS (SELECT 1 FROM table WHERE id=3);
With Postgres 9.1 it is possible to do it with one query: https://stackoverflow.com/a/1109198/2873507
code:
class Main
{
public static void main(String[] args)
{
int a=10, b=20;
System.out.println(a + " " + b);
}
}
Input: none
Output: 10 20
server.port = 0
for random port
server.port
= 8080 for custom 8080 port
I just set the timezone with Matthias Bauch answer And it worked for me. else it was adding 18:30 min more.
let cal: NSCalendar = NSCalendar.currentCalendar()
cal.timeZone = NSTimeZone(forSecondsFromGMT: 0)
let newDate: NSDate = cal.dateBySettingHour(1, minute: 0, second: 0, ofDate: NSDate(), options: NSCalendarOptions())!
Since this thread is a popular result in google search, here is the way to do it for sublime text 3 build 3059+: in user preferences, add the line:
"show_encoding": true
$("#my_select").select2('destroy').empty().select2({data: [{id: 1, text: "new_item"}]});
Below step solved my issue:
Open CMD
Prompt with Admin Privileges.
Run : iisreset.
Hope this helps.
You can do this using the Class.cast()
method, which dynamically casts the supplied parameter to the type of the class instance you have. To get the class instance of a particular field, you use the getType()
method on the field in question. I've given an example below, but note that it omits all error handling and shouldn't be used unmodified.
public class Test {
public String var1;
public Integer var2;
}
public class Main {
public static void main(String[] args) throws Exception {
Map<String, Object> map = new HashMap<String, Object>();
map.put("var1", "test");
map.put("var2", 1);
Test t = new Test();
for (Map.Entry<String, Object> entry : map.entrySet()) {
Field f = Test.class.getField(entry.getKey());
f.set(t, f.getType().cast(entry.getValue()));
}
System.out.println(t.var1);
System.out.println(t.var2);
}
}
Dashes (-
) have no significance other than making the number more readable, so you might as well include them.
Since we never know where our website visitors are coming from, we need to make phone numbers callable from anywhere in the world. For this reason the +
sign is always necessary. The +
sign is automatically converted by your mobile carrier to your international dialing prefix, also known as "exit code". This code varies by region, country, and sometimes a single country can use multiple codes, depending on the carrier. Fortunately, when it is a local call, dialing it with the international format will still work.
Using your example number, when calling from China, people would need to dial:
00-1-555-555-1212
And from Russia, they would dial
810-1-555-555-1212
The +
sign solves this issue by allowing you to omit the international dialing prefix.
After the international dialing prefix comes the country code(pdf), followed by the geographic code (area code), finally the local phone number.
Therefore either of the last two of your examples would work, but my recommendation is to use this format for readability:
<a href="tel:+1-555-555-1212">+1-555-555-1212</a>
Note: For numbers that contain a trunk prefix different from the country code (e.g. if you write it locally with brackets around a 0
), you need to omit it because the number must be in international format.
I don't see why Microsoft didn't handle this. A smart little utility method to deal with this (I had the issue with int, but replacing int with DateTime will be the same effect, could be.....
public static bool NullableValueTryParse(string text, out int? nInt)
{
int value;
if (int.TryParse(text, out value))
{
nInt = value;
return true;
}
else
{
nInt = null;
return false;
}
}
In case you want to increase the font of the labels of the histogram when setting labels=TRUE
bp=hist(values, labels = FALSE,
main='Histogram',
xlab='xlab',ylab='ylab', cex.main=2, cex.lab=2,cex.axis=2)
text(x=bp$mids, y=bp$counts, labels=bp$counts ,cex=2,pos=3)
Ok...so first you need to import the image into your project.
1) Select the PictureBox in the Form Design View
2) Open PictureBox Tasks
(it's the little arrow printed to right on the edge of the PictureBox)
3) Click on "Choose image..."
4) Select the second option "Project resource file:"
(this option will create a folder called "Resources" which you can access with Properties.Resources)
5) Click on "Import..." and select your image from your computer
(now a copy of the image will be saved in "Resources" folder created at step 4)
6) Click on "OK"
Now the image is in your project and you can use it with the Properties command. Just type this code when you want to change the picture in the PictureBox:
pictureBox1.Image = Properties.Resources.MyImage;
Note:
MyImage represent the name of the image...
After typing "Properties.Resources.", all imported image files are displayed...
No, VBA does not have this functionality. You can use the technique of adding each item to a collection using the item as the key. Since a collection does not allow duplicate keys, the result is distinct values that you can copy to an array, if needed.
You may also want something more robust. See Distinct Values Function at http://www.cpearson.com/excel/distinctvalues.aspx
Distinct Values Function
A VBA Function that will return an array of the distinct values in a range or array of input values.
Excel has some manual methods, such as Advanced Filter, for getting a list of distinct items from an input range. The drawback of using such methods is that you must manually refresh the results when the input data changes. Moreover, these methods work only with ranges, not arrays of values, and, not being functions, cannot be called from worksheet cells or incorporated into array formulas. This page describes a VBA function called DistinctValues that accepts as input either a range or an array of data and returns as its result an array containing the distinct items from the input list. That is, the elements with all duplicates removed. The order of the input elements is preserved. The order of the elements in the output array is the same as the order in the input values. The function can be called from an array entered range on a worksheet (see this page for information about array formulas), or from in an array formula in a single worksheet cell, or from another VB function.
My problem was my Target profile didn't have the proper code signing option selected:
Target Menu -> Code Signing -> Code Signing Identity
Choose "iPhone developer" then select the provisional profile you created.
Try this:
SELECT left(right(cast(SampleText as nVarchar),LEN(cast(sampleText as nVarchar))-1),LEN(cast(sampleText as nVarchar))-2)
FROM TableName
I am using in the way and it is working for me.
public static void main(String[] args) {
new CarpoolDBAppTest();
}
public CarpoolDBAppTest(){
ApplicationContext context = new ClassPathXmlApplicationContext("application-context.xml");
Student stud = (Student) context.getBean("yourBeanId");
}
Here Student is my classm you will get the class matching yourBeanId.
Now work on that object with whatever operation you want to do.
Typically if you have database connections or other objects declared that, whether used safely or created prior to your exception, will need to be cleaned up (disposed of), then returning your error handling code back to the ProcExit entry point will allow you to do your garbage collection in both cases.
If you drop out of your procedure by falling to Exit Sub, you may risk having a yucky build-up of instantiated objects that are just sitting around in your program's memory.
If you have a PPK file working on a PC, then export it as OpenSSH file using puttygen.exe for PC and use that on Mac (any Unix machine).
I was getting the same error --
debug1: Authentications that can continue: publickey,gssapi-with-mic
debug1: Next authentication method: publickey
debug1: Trying private key: ec2-keypair
debug1: read PEM private key done: type RSA
debug1: Authentications that can continue: publickey,gssapi-with-mic
debug1: No more authentication methods to try.
Permission denied (publickey,gssapi-with-mic)
As I was using a PPK file on Windows, I followed the steps as described above and Bingo!
$ ssh -i ec2-openssh-key root@ec2-instance-ip
Remove the file from the index, but keep it versioned and left with uncommitted changes in working copy:
git reset head <file>
Reset the file to the last state from HEAD, undoing changes and removing them from the index:
git reset HEAD <file>
git checkout <file>
# If you have a `<branch>` named like `<file>`, use:
git checkout -- <file>
This is needed since git reset --hard HEAD
won't work with single files.
Remove <file>
from index and versioning, keeping the un-versioned file with changes in working copy:
git rm --cached <file>
Remove <file>
from working copy and versioning completely:
git rm <file>
You want to use slicing.
for item in listOfStuff[1:3]:
print item
I did not manage to find a way to do it directly.
Instead I imported the bak file into SQL Server 2008 Express, and then used MySQL Migration Toolkit.
Worked like a charm!
REST
I understand the main idea of REST is extremely simple. We have used web browsers for years and we have seen how easy, flexible, performing, etc web sites are. HTML sites use hyperlinks and forms as the primary means of user interaction. Their main goal is to allow us, clients, to know only those links that we can use in the current state. And REST simply says 'why not use the same principles to drive computer rather than human clients through our application?' Combine this with the power of the WWW infrastructure and you'll get a killer tool for building great distributed applications.
Another possible explanation is for mathematically thinking people. Each application is basically a state machine with business logic actions being state transitions. The idea of REST is to map each transition onto some request to a resource and provide clients with links representing transitions available in the current state. Thus it models the state machine via representations and links. This is why it's called REpresentational State Transfer.
It's quite surprising that all answers seem to focus either on message format, or on HTTP verbs usage. In fact, the message format doesn't matter at all, REST can use any one provided that the service developer documents it. HTTP verbs only make a service a CRUD service, but not yet RESTful. What really turns a service into a REST service are hyperlinks (aka hypermedia controls) embedded into server responses together with data, and their amount must be enough for any client to choose the next action from those links.
Unfortunately, it's rather difficult to find correct info on REST on the Web, except for the Roy Fielding's thesis. (He's the one who derived REST). I would recommend the 'REST in Practice' book as it gives a comprehensive step-by-step tutorial on how to evolve from SOAP to REST.
SOAP
This is one of the possible forms of RPC (remote procedure call) architecture style. In essence, it's just a technology that allows clients call methods of server via service boundaries (network, processes, etc) as if they were calling local methods. Of course, it actually differs from calling local methods in speed, reliability and so on, but the idea is that simple.
Compared
The details like transport protocols, message formats, xsd, wsdl, etc. don't matter when comparing any form of RPC to REST. The main difference is that an RPC service reinvents bicycle by designing it's own application protocol in the RPC API with the semantics that only it knows. Therefore, all clients have to understand this protocol prior to using the service, and no generic infrastructure like caches can be built because of proprietary semantics of all requests. Furthermore, RPC APIs do not suggest what actions are allowed in the current state, this has to be derived from additional documentation. REST on the other hand implies using uniform interfaces to allow various clients to have some understanding of API semantics, and hypermedia controls (links) to highlight available options in each state. Thus, it allows for caching responses to scale services and making correct API usage easily discoverable without additional documentation.
In a way, SOAP (as any other RPC) is an attempt to tunnel through a service boundary treating the connecting media as a black box capable of transmitting messages only. REST is a decision to acknowledge that the Web is a huge distributed information system, to accept the world as is and learn to master it instead of fighting against it.
SOAP seems to be great for internal network APIs, when you control both the server and the clients, and while the interactions are not too complex. It's more natural for developers to use it. However, for a public API that is used by many independent parties, is complex and big, REST should fit better. But this last comparison is very fuzzy.
Update
My experience has unexpectedly shown REST development to be more difficult than SOAP. At least for .NET. While there are great frameworks like ASP.NET Web API, there's no tooling that would automatically generate client-side proxy. Nothing like 'Add Web Service Reference' or 'Add WCF Service Reference'. One has to write all serialization and service querying code by hand. And man, that's lots of boilerplate code. I think REST development needs something similar to WSDL and tooling implementation for each development platform. In fact, there seems to be a good ground: WADL or WSDL 2.0, but neither of the standards seems to be well-supported.
Update (Jan 2016)
Turns out there is now a wide variety of tools for REST API definition. My personal preference is currently RAML.
How Web Services work
Well, this is a too broad question, because it depends on the architecture and technology used in the specific web service. But in general, a web service is simply some application in the Web that can accept requests from clients and return responses. It's exposed to the Web, thus it's a web service, and it's typically available 24/7, that's why it's a service. Of course, it solves some problem (otherwise why would someone ever use a web service) for its clients.
It is possible to use Object.defineProperty()
in order to redefine the 'value' property of the input element and do anything during its changing.
Object.defineProperty()
allows us to define a getter and setter for a property, thus controlling it.
replaceWithWrapper($("#hid1")[0], "value", function(obj, property, value) {
console.log("new value:", value)
});
function replaceWithWrapper(obj, property, callback) {
Object.defineProperty(obj, property, new function() {
var _value = obj[property];
return {
set: function(value) {
_value = value;
callback(obj, property, value)
},
get: function() {
return _value;
}
}
});
}
$("#hid1").val(4);
I will give you a better idea
for(decltype(things.size()) i = 0; i < things.size(); i++){
//...
}
decltype
is
Inspects the declared type of an entity or the type and value category of an expression.
So, It deduces type of things.size()
and i
will be a type as same as things.size()
. So,
i < things.size()
will be executed without any warning
There are three ways to describe a table in Hive.
1) To see table primary info of Hive table, use describe table_name; command
2) To see more detailed information about the table, use describe extended table_name; command
3) To see code in a clean manner use describe formatted table_name; command to see all information. also describe all details in a clean manner.
Resource: Hive interview tips
Like Andrew said /exclude
parameter of xcopy should be existing file that has list of excludes.
Documentation of xcopy says:
Using /exclude
List each string in a separate line in each file. If any of the listed strings match any part of the absolute path of the file to be copied, that file is then excluded from the copying process. For example, if you specify the string "\Obj\", you exclude all files underneath the Obj directory. If you specify the string ".obj", you exclude all files with the .obj extension.
Example:
xcopy c:\t1 c:\t2 /EXCLUDE:list-of-excluded-files.txt
and list-of-excluded-files.txt
should exist in current folder (otherwise pass full path), with listing of files/folders to exclude - one file/folder per line. In your case that would be:
exclusion.txt
it doesn't matter that you declare your minSdk in build.gradle. You have to copy overrideLibrary
in your AndroidManifest.xml
, as documented here.
<manifest
... >
<uses-sdk tools:overrideLibrary="com.example.lib1, com.example.lib2"/>
...
</manifest>
The system automatically ignores the sdkVersion declared in AndroidManifest.xml.
I hope this solve your problem.
Copy below code and paste AndroidManifest.xml file in under First Activity Tag.
<activity
android:name="com.SplashActivity"
android:clearTaskOnLaunch="true"
android:launchMode="singleTask"
android:excludeFromRecents="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER"
/>
</intent-filter>
</activity>
Also Add this below code in all under Activity Tag in AndroidManifest.xml file
android:finishOnTaskLaunch="true"
Note
Mutation events have been deprecated since this post was written, and may not be supported by all browsers. Instead, use a mutation observer.
Yes you can. DOM L2 Events module defines mutation events; one of them - DOMAttrModified is the one you need. Granted, these are not widely implemented, but are supported in at least Gecko and Opera browsers.
Try something along these lines:
document.documentElement.addEventListener('DOMAttrModified', function(e){
if (e.attrName === 'style') {
console.log('prevValue: ' + e.prevValue, 'newValue: ' + e.newValue);
}
}, false);
document.documentElement.style.display = 'block';
You can also try utilizing IE's "propertychange" event as a replacement to DOMAttrModified
. It should allow to detect style
changes reliably.
The code was most likely compiled with a later JDK (without using cross-compilation options) and is being run on an earlier JRE. While upgrading the JRE is one solution, it would be better to use the cross-compilation options to ensure the code will run on whatever JRE is intended as the minimum version for the app.
This is the class where the connection is established and messages are recieved. Make sure to pair the devices before you run the application. If you want to have a slave/master connection, where each slave can only send messages to the master , and the master can broadcast messages to all slaves. You should only pair the master with each slave , but you shouldn't pair the slaves together.
package com.example.gaby.coordinatorv1;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Set;
import java.util.UUID;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;
public class Piconet {
private final static String TAG = Piconet.class.getSimpleName();
// Name for the SDP record when creating server socket
private static final String PICONET = "ANDROID_PICONET_BLUETOOTH";
private final BluetoothAdapter mBluetoothAdapter;
// String: device address
// BluetoothSocket: socket that represent a bluetooth connection
private HashMap<String, BluetoothSocket> mBtSockets;
// String: device address
// Thread: thread for connection
private HashMap<String, Thread> mBtConnectionThreads;
private ArrayList<UUID> mUuidList;
private ArrayList<String> mBtDeviceAddresses;
private Context context;
private Handler handler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case 1:
Toast.makeText(context, msg.getData().getString("msg"), Toast.LENGTH_SHORT).show();
break;
default:
break;
}
};
};
public Piconet(Context context) {
this.context = context;
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
mBtSockets = new HashMap<String, BluetoothSocket>();
mBtConnectionThreads = new HashMap<String, Thread>();
mUuidList = new ArrayList<UUID>();
mBtDeviceAddresses = new ArrayList<String>();
// Allow up to 7 devices to connect to the server
mUuidList.add(UUID.fromString("a60f35f0-b93a-11de-8a39-08002009c666"));
mUuidList.add(UUID.fromString("54d1cc90-1169-11e2-892e-0800200c9a66"));
mUuidList.add(UUID.fromString("6acffcb0-1169-11e2-892e-0800200c9a66"));
mUuidList.add(UUID.fromString("7b977d20-1169-11e2-892e-0800200c9a66"));
mUuidList.add(UUID.fromString("815473d0-1169-11e2-892e-0800200c9a66"));
mUuidList.add(UUID.fromString("503c7434-bc23-11de-8a39-0800200c9a66"));
mUuidList.add(UUID.fromString("503c7435-bc23-11de-8a39-0800200c9a66"));
Thread connectionProvider = new Thread(new ConnectionProvider());
connectionProvider.start();
}
public void startPiconet() {
Log.d(TAG, " -- Looking devices -- ");
// The devices must be already paired
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter
.getBondedDevices();
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
// X , Y and Z are the Bluetooth name (ID) for each device you want to connect to
if (device != null && (device.getName().equalsIgnoreCase("X") || device.getName().equalsIgnoreCase("Y")
|| device.getName().equalsIgnoreCase("Z") || device.getName().equalsIgnoreCase("M"))) {
Log.d(TAG, " -- Device " + device.getName() + " found --");
BluetoothDevice remoteDevice = mBluetoothAdapter
.getRemoteDevice(device.getAddress());
connect(remoteDevice);
}
}
} else {
Toast.makeText(context, "No paired devices", Toast.LENGTH_SHORT).show();
}
}
private class ConnectionProvider implements Runnable {
@Override
public void run() {
try {
for (int i=0; i<mUuidList.size(); i++) {
BluetoothServerSocket myServerSocket = mBluetoothAdapter
.listenUsingRfcommWithServiceRecord(PICONET, mUuidList.get(i));
Log.d(TAG, " ** Opened connection for uuid " + i + " ** ");
// This is a blocking call and will only return on a
// successful connection or an exception
Log.d(TAG, " ** Waiting connection for socket " + i + " ** ");
BluetoothSocket myBTsocket = myServerSocket.accept();
Log.d(TAG, " ** Socket accept for uuid " + i + " ** ");
try {
// Close the socket now that the
// connection has been made.
myServerSocket.close();
} catch (IOException e) {
Log.e(TAG, " ** IOException when trying to close serverSocket ** ");
}
if (myBTsocket != null) {
String address = myBTsocket.getRemoteDevice().getAddress();
mBtSockets.put(address, myBTsocket);
mBtDeviceAddresses.add(address);
Thread mBtConnectionThread = new Thread(new BluetoohConnection(myBTsocket));
mBtConnectionThread.start();
Log.i(TAG," ** Adding " + address + " in mBtDeviceAddresses ** ");
mBtConnectionThreads.put(address, mBtConnectionThread);
} else {
Log.e(TAG, " ** Can't establish connection ** ");
}
}
} catch (IOException e) {
Log.e(TAG, " ** IOException in ConnectionService:ConnectionProvider ** ", e);
}
}
}
private class BluetoohConnection implements Runnable {
private String address;
private final InputStream mmInStream;
public BluetoohConnection(BluetoothSocket btSocket) {
InputStream tmpIn = null;
try {
tmpIn = new DataInputStream(btSocket.getInputStream());
} catch (IOException e) {
Log.e(TAG, " ** IOException on create InputStream object ** ", e);
}
mmInStream = tmpIn;
}
@Override
public void run() {
byte[] buffer = new byte[1];
String message = "";
while (true) {
try {
int readByte = mmInStream.read();
if (readByte == -1) {
Log.e(TAG, "Discarting message: " + message);
message = "";
continue;
}
buffer[0] = (byte) readByte;
if (readByte == 0) { // see terminateFlag on write method
onReceive(message);
message = "";
} else { // a message has been recieved
message += new String(buffer, 0, 1);
}
} catch (IOException e) {
Log.e(TAG, " ** disconnected ** ", e);
}
mBtDeviceAddresses.remove(address);
mBtSockets.remove(address);
mBtConnectionThreads.remove(address);
}
}
}
/**
* @param receiveMessage
*/
private void onReceive(String receiveMessage) {
if (receiveMessage != null && receiveMessage.length() > 0) {
Log.i(TAG, " $$$$ " + receiveMessage + " $$$$ ");
Bundle bundle = new Bundle();
bundle.putString("msg", receiveMessage);
Message message = new Message();
message.what = 1;
message.setData(bundle);
handler.sendMessage(message);
}
}
/**
* @param device
* @param uuidToTry
* @return
*/
private BluetoothSocket getConnectedSocket(BluetoothDevice device, UUID uuidToTry) {
BluetoothSocket myBtSocket;
try {
myBtSocket = device.createRfcommSocketToServiceRecord(uuidToTry);
myBtSocket.connect();
return myBtSocket;
} catch (IOException e) {
Log.e(TAG, "IOException in getConnectedSocket", e);
}
return null;
}
private void connect(BluetoothDevice device) {
BluetoothSocket myBtSocket = null;
String address = device.getAddress();
BluetoothDevice remoteDevice = mBluetoothAdapter.getRemoteDevice(address);
// Try to get connection through all uuids available
for (int i = 0; i < mUuidList.size() && myBtSocket == null; i++) {
// Try to get the socket 2 times for each uuid of the list
for (int j = 0; j < 2 && myBtSocket == null; j++) {
Log.d(TAG, " ** Trying connection..." + j + " with " + device.getName() + ", uuid " + i + "...** ");
myBtSocket = getConnectedSocket(remoteDevice, mUuidList.get(i));
if (myBtSocket == null) {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
Log.e(TAG, "InterruptedException in connect", e);
}
}
}
}
if (myBtSocket == null) {
Log.e(TAG, " ** Could not connect ** ");
return;
}
Log.d(TAG, " ** Connection established with " + device.getName() +"! ** ");
mBtSockets.put(address, myBtSocket);
mBtDeviceAddresses.add(address);
Thread mBluetoohConnectionThread = new Thread(new BluetoohConnection(myBtSocket));
mBluetoohConnectionThread.start();
mBtConnectionThreads.put(address, mBluetoohConnectionThread);
}
public void bluetoothBroadcastMessage(String message) {
//send message to all except Id
for (int i = 0; i < mBtDeviceAddresses.size(); i++) {
sendMessage(mBtDeviceAddresses.get(i), message);
}
}
private void sendMessage(String destination, String message) {
BluetoothSocket myBsock = mBtSockets.get(destination);
if (myBsock != null) {
try {
OutputStream outStream = myBsock.getOutputStream();
final int pieceSize = 16;
for (int i = 0; i < message.length(); i += pieceSize) {
byte[] send = message.substring(i,
Math.min(message.length(), i + pieceSize)).getBytes();
outStream.write(send);
}
// we put at the end of message a character to sinalize that message
// was finished
byte[] terminateFlag = new byte[1];
terminateFlag[0] = 0; // ascii table value NULL (code 0)
outStream.write(new byte[1]);
} catch (IOException e) {
Log.d(TAG, "line 278", e);
}
}
}
}
Your main activity should be as follow :
package com.example.gaby.coordinatorv1;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
private Button discoveryButton;
private Button messageButton;
private Piconet piconet;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
piconet = new Piconet(getApplicationContext());
messageButton = (Button) findViewById(R.id.messageButton);
messageButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
piconet.bluetoothBroadcastMessage("Hello World---*Gaby Bou Tayeh*");
}
});
discoveryButton = (Button) findViewById(R.id.discoveryButton);
discoveryButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
piconet.startPiconet();
}
});
}
}
And here's the XML Layout :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<Button
android:id="@+id/discoveryButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Discover"
/>
<Button
android:id="@+id/messageButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Send message"
/>
Do not forget to add the following permissions to your Manifest File :
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
System.Net.WebException: The remote server returned an error: (411) Length Required.
This is a pretty common issue that comes up when trying to make call a REST based API method through POST. Luckily, there is a simple fix for this one.
This is the code I was using to call the Windows Azure Management API. This particular API call requires the request method to be set as POST, however there is no information that needs to be sent to the server.
var request = (HttpWebRequest) HttpWebRequest.Create(requestUri);
request.Headers.Add("x-ms-version", "2012-08-01"); request.Method =
"POST"; request.ContentType = "application/xml";
To fix this error, add an explicit content length to your request before making the API call.
request.ContentLength = 0;
I had this issue while using RestAssured with JUnit. For me this programmatic approach worked:
@BeforeClass
public static void setUpClass() {
ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) org.slf4j.LoggerFactory.getLogger("org.apache.http");
root.setLevel(ch.qos.logback.classic.Level.INFO);
//...
}
About horrible code:
int& getTheValue()
{
return *new int;
}
So, indeed, memory pointer lost after return. But if you use shared_ptr like that:
int& getTheValue()
{
std::shared_ptr<int> p(new int);
return *p->get();
}
Memory not lost after return and will be freed after assignment.
Not quite, although generally you can usually use some workaround on one of the forms
[^abc]
, which is character by character not a
or b
or c
, a(?!b)
, which is a
not followed by b
(?<!a)b
, which is b
not preceeded by a
As people above have noted you'll either have to recalculate an offset to the stroke's path coordinates or double its width and then mask one side or the other, because not only does SVG not natively support Illustrator's stroke alignment, but PostScript doesn't either.
The specification for strokes in Adobe's PostScript Manual 2nd edition states: "4.5.1 Stroking: The stroke operator draws a line of some thickness along the current path. For each straight or curved segment in the path, stroke draws a line that is centered on the segment with sides parallel to the segment." (emphasis theirs)
The rest of the specification has no attributes for offsetting the line's position. When Illustrator lets you align inside or outside, it's recalculating the actual path's offset (because it's still computationally cheaper than overprinting then masking). The path coordinates in the .ai document are reference, not what gets rastered or exported to a final format.
Because Inkscape's native format is spec SVG, it can't offer a feature the spec lacks.
Another important difference is that the Hashtable type supports lock-free multiple readers and a single writer at the same time, while Dictionary does not.
If your just interested in sharing complex data types between javascript and python, check out jsonpickle. It wraps the standard Python JSON libraries, but has some smarts in serializing and deserializing Python classes and other data types.
Quite a few Google App Engine projects have used this library. Joose and FirePython both incorporate jsonpickle.
Short answer no :)
But you could just use the same CSS for the hover like so:
a:hover, .hoverclass {
background:red;
}
Maybe if you explain why you need the class added, there may be a better solution?
How about the assign
member function?
some_vector.assign(some_vector.size(), 0);
This is an error that is some how had to debug. As it has been said many times, improper import/export can cause this error but surprisingly i got this error from a small bug in my react-router-dom authentication setup
below is my case:
WRONG SETUP:
const PrivateRoute = ({ component: Component, ...rest }) => (
<Route
{...rest}
render={(props) => (token ? <Component {...props} /> : <Redirect to={{ pathname: "/login" }} />)}
/>
);
CORRECT SETUP:
const PrivateRoute = ({ component: Component, token, ...rest }) => (
<Route
{...rest}
render={(props) => (token ? <Component {...props} /> : <Redirect to={{ pathname: "/login" }} />)}
/>
);
The only difference was I was deconstructing the token
in the PrivateRoute component
. By the way the token is gotten from localstorage
like this const token = localStorage.getItem("authUser");
so if it is not there I know the user is not authenticated. This can also cause that error.
It sounds like your m2eclipse install is using the embedded Maven, which has its own repository (located under user home) and settings.
If you open up the Maven preferences (Window->Preferences->Maven->Installations, you can add your Maven installation by selecting Add... then browsing to the M2_HOME directory.
(source: sonatype.com)
For more details see the m2eclipse book
You can achieve this with MAVEN_OPTS, for example
MAVEN_OPTS=-Dorg.slf4j.simpleLogger.defaultLogLevel=warn mvn clean
Rather than putting the system property directly on the command line. (At least for maven 3.3.1.)
Consider using ~/.mavenrc
for setting MAVEN_OPTS
if you would like logging changed for your login across all maven invocations.
Return as a tuple, e.g.
def foo (a):
x=a
y=a*2
return (x,y)
For normal DateTimes, if you don't initialize them at all then they will match DateTime.MinValue
, because it is a value type rather than a reference type.
You can also use a nullable DateTime, like this:
DateTime? MyNullableDate;
Or the longer form:
Nullable<DateTime> MyNullableDate;
And, finally, there's a built in way to reference the default of any type. This returns null
for reference types, but for our DateTime example it will return the same as DateTime.MinValue
:
default(DateTime)
or, in more recent versions of C#,
default
You can do like this
$.datepicker.regional['fr'] = {clearText: 'Effacer', clearStatus: '',
closeText: 'Fermer', closeStatus: 'Fermer sans modifier',
prevText: '<Préc', prevStatus: 'Voir le mois précédent',
nextText: 'Suiv>', nextStatus: 'Voir le mois suivant',
currentText: 'Courant', currentStatus: 'Voir le mois courant',
monthNames: ['Janvier','Février','Mars','Avril','Mai','Juin',
'Juillet','Août','Septembre','Octobre','Novembre','Décembre'],
monthNamesShort: ['Jan','Fév','Mar','Avr','Mai','Jun',
'Jul','Aoû','Sep','Oct','Nov','Déc'],
monthStatus: 'Voir un autre mois', yearStatus: 'Voir un autre année',
weekHeader: 'Sm', weekStatus: '',
dayNames: ['Dimanche','Lundi','Mardi','Mercredi','Jeudi','Vendredi','Samedi'],
dayNamesShort: ['Dim','Lun','Mar','Mer','Jeu','Ven','Sam'],
dayNamesMin: ['Di','Lu','Ma','Me','Je','Ve','Sa'],
dayStatus: 'Utiliser DD comme premier jour de la semaine', dateStatus: 'Choisir le DD, MM d',
dateFormat: 'dd/mm/yy', firstDay: 0,
initStatus: 'Choisir la date', isRTL: false};
$.datepicker.setDefaults($.datepicker.regional['fr']);
Here's the NON-jQuery solution that instantly removes the address bar without scrolling. Also, it works when you rotate the browser's orientation.
function hideAddressBar(){
if(document.documentElement.scrollHeight<window.outerHeight/window.devicePixelRatio)
document.documentElement.style.height=(window.outerHeight/window.devicePixelRatio)+'px';
setTimeout(window.scrollTo(1,1),0);
}
window.addEventListener("load",function(){hideAddressBar();});
window.addEventListener("orientationchange",function(){hideAddressBar();});
It should work with the iPhone also, but I couldn't test this.
Here's a java example using DesiredCapabilities
. I used it for pumping selenium tests into jmeter. (was only interested in HTTP requests)
import org.openqa.selenium.Proxy;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
String myProxy = "localhost:7777"; //example: proxy host=localhost port=7777
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(CapabilityType.PROXY,
new Proxy().setHttpProxy(myProxy));
WebDriver webDriver = new FirefoxDriver(capabilities);
.net core
using System.Text.Json;
var jsonStr = JsonSerializer.Serialize(MyObject)
var weatherForecast = JsonSerializer.Deserialize<MyObject>(jsonStr);
For more information about excluding properties and nulls check out This Microsoft side