If my compiler is set to 32 bit, size_t
is nothing other than a typedef for unsigned int
. If my compiler is set to 64 bit, size_t
is nothing other than a typedef for unsigned long long
.
size_t
is a very readable way to specify the size dimension of an item - length of a string, amount of bytes a pointer takes, etc.
It's also portable across platforms - you'll find that 64bit and 32bit both behave nicely with system functions and size_t
- something that unsigned int
might not do (e.g. when should you use unsigned long
size_t is defined by the C standard to be the unsigned integer return type of the sizeof operator (C99 6.3.5.4.4), and the argument of malloc and friends (C99 7.20.3.3 etc). The actual range is set such that the maximum (SIZE_MAX) is at least 65535 (C99 7.18.3.2).
However, this doesn't let us determine sizeof(size_t). The implementation is free to use any representation it likes for size_t - so there is no upper bound on size - and the implementation is also free to define a byte as 16-bits, in which case size_t can be equivalent to unsigned char.
Putting that aside, however, in general you'll have 32-bit size_t on 32-bit programs, and 64-bit on 64-bit programs, regardless of the data model. Generally the data model only affects static data; for example, in GCC:
`-mcmodel=small'
Generate code for the small code model: the program and its
symbols must be linked in the lower 2 GB of the address space.
Pointers are 64 bits. Programs can be statically or dynamically
linked. This is the default code model.
`-mcmodel=kernel'
Generate code for the kernel code model. The kernel runs in the
negative 2 GB of the address space. This model has to be used for
Linux kernel code.
`-mcmodel=medium'
Generate code for the medium model: The program is linked in the
lower 2 GB of the address space but symbols can be located
anywhere in the address space. Programs can be statically or
dynamically linked, but building of shared libraries are not
supported with the medium model.
`-mcmodel=large'
Generate code for the large model: This model makes no assumptions
about addresses and sizes of sections.
You'll note that pointers are 64-bit in all cases; and there's little point to having 64-bit pointers but not 64-bit sizes, after all.
If your code is prepared to deal with overflow errors, you can throw an exception if data
is too large.
size_t data = 99999999;
if ( data > INT_MAX )
{
throw std::overflow_error("data is larger than INT_MAX");
}
int convertData = static_cast<int>(data);
ssize_t
is not included in the standard and isn't portable. size_t
should be used when handling the size of objects (there's ptrdiff_t
too, for pointer differences).
From my understanding, size_t
is an unsigned
integer whose bit size is large enough to hold a pointer of the native architecture.
So:
sizeof(size_t) >= sizeof(void*)
(apply on Mac, and probably other Unixes)
Actually there is a problem with the wc approach: it does not count the last line if it does not terminate with the end of line symbol.
Use this instead
nbLines=$(cat -n file.txt | tail -n 1 | cut -f1 | xargs)
or even better (thanks gniourf_gniourf):
nblines=$(grep -c '' file.txt)
Note: The awk approach by chilicuil also works.
No, objects don't have a built in identifier, though you can add one by modifying the object prototype. Here's an example of how you might do that:
(function() {
var id = 0;
function generateId() { return id++; };
Object.prototype.id = function() {
var newId = generateId();
this.id = function() { return newId; };
return newId;
};
})();
That said, in general modifying the object prototype is considered very bad practice. I would instead recommend that you manually assign an id to objects as needed or use a touch
function as others have suggested.
Your delete code looks like this
Gridview1.DeleteRow(e.RowIndex);
Gridview1.DataBind();
When you call Gridview1.DataBind() you will populate your gridview with the current datasource. So, it will delete all the existent rows, and it will add all the rows from CustomersSqlDataSource.
What you need to do is delete the row from the table that CustomersSqlDataSource querying.
You can do this very easy by setting a delete command to CustomersSqlDataSource, add a delete parameter, and then execute the delete command.
CustomersSqlDataSource.DeleteCommand = "DELETE FROM Customer Where CustomerID=@CustomerID"; // Customer is the name of the table where you take your data from. Maybe you named it different
CustomersSqlDataSource.DeleteParameters.Add("CustomerID", Gridview1.DataKeys[e.RowIndex].Values["CustomerID"].ToString());
CustomersSqlDataSource.Delete();
Gridview1.DataBind();
But take into account that this will delete the data from the database.
Set your header and footer position to "absolute" and that should do the trick. Hope it helps and good luck with your project!
Simple Image upload in codeigniter
Find below code for easy image upload
public function doupload()
{
$upload_path="https://localhost/project/profile"
$uid='10'; //creare seperate folder for each user
$upPath=upload_path."/".$uid;
if(!file_exists($upPath))
{
mkdir($upPath, 0777, true);
}
$config = array(
'upload_path' => $upPath,
'allowed_types' => "gif|jpg|png|jpeg",
'overwrite' => TRUE,
'max_size' => "2048000",
'max_height' => "768",
'max_width' => "1024"
);
$this->load->library('upload', $config);
if(!$this->upload->do_upload('userpic'))
{
$data['imageError'] = $this->upload->display_errors();
}
else
{
$imageDetailArray = $this->upload->data();
$image = $imageDetailArray['file_name'];
}
}
Hope this helps you to upload image
You should wrap your recursive function call into a
setTimeout
,setImmediate
or process.nextTick
function to give node.js the chance to clear the stack. If you don't do that and there are many loops without any real async function call or if you do not wait for the callback, your RangeError: Maximum call stack size exceeded
will be inevitable.
There are many articles concerning "Potential Async Loop". Here is one.
Now some more example code:
// ANTI-PATTERN
// THIS WILL CRASH
var condition = false, // potential means "maybe never"
max = 1000000;
function potAsyncLoop( i, resume ) {
if( i < max ) {
if( condition ) {
someAsyncFunc( function( err, result ) {
potAsyncLoop( i+1, callback );
});
} else {
// this will crash after some rounds with
// "stack exceed", because control is never given back
// to the browser
// -> no GC and browser "dead" ... "VERY BAD"
potAsyncLoop( i+1, resume );
}
} else {
resume();
}
}
potAsyncLoop( 0, function() {
// code after the loop
...
});
This is right:
var condition = false, // potential means "maybe never"
max = 1000000;
function potAsyncLoop( i, resume ) {
if( i < max ) {
if( condition ) {
someAsyncFunc( function( err, result ) {
potAsyncLoop( i+1, callback );
});
} else {
// Now the browser gets the chance to clear the stack
// after every round by getting the control back.
// Afterwards the loop continues
setTimeout( function() {
potAsyncLoop( i+1, resume );
}, 0 );
}
} else {
resume();
}
}
potAsyncLoop( 0, function() {
// code after the loop
...
});
Now your loop may become too slow, because we loose a little time (one browser roundtrip) per round. But you do not have to call setTimeout
in every round. Normally it is o.k. to do it every 1000th time. But this may differ depending on your stack size:
var condition = false, // potential means "maybe never"
max = 1000000;
function potAsyncLoop( i, resume ) {
if( i < max ) {
if( condition ) {
someAsyncFunc( function( err, result ) {
potAsyncLoop( i+1, callback );
});
} else {
if( i % 1000 === 0 ) {
setTimeout( function() {
potAsyncLoop( i+1, resume );
}, 0 );
} else {
potAsyncLoop( i+1, resume );
}
}
} else {
resume();
}
}
potAsyncLoop( 0, function() {
// code after the loop
...
});
I would like to suggest an improvement to yanchenko's answer.
Instead of taking the first ip in the X_FORWARDED_FOR list, I take the first one which in not a known internal ip, as some routers don't respect the protocol, and you can see internal ips as the first value of the list.
PRIVATE_IPS_PREFIX = ('10.', '172.', '192.', )
def get_client_ip(request):
"""get the client ip from the request
"""
remote_address = request.META.get('REMOTE_ADDR')
# set the default value of the ip to be the REMOTE_ADDR if available
# else None
ip = remote_address
# try to get the first non-proxy ip (not a private ip) from the
# HTTP_X_FORWARDED_FOR
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
if x_forwarded_for:
proxies = x_forwarded_for.split(',')
# remove the private ips from the beginning
while (len(proxies) > 0 and
proxies[0].startswith(PRIVATE_IPS_PREFIX)):
proxies.pop(0)
# take the first ip which is not a private one (of a proxy)
if len(proxies) > 0:
ip = proxies[0]
return ip
I hope this helps fellow Googlers who have the same problem.
Look at this blog here. It describes a way to do this, by defining an EntitySorter<T>
.
It allows you to pass in an IEntitySorter<T>
into your service methods and use it like this:
public static Person[] GetAllPersons(IEntitySorter<Person> sorter)
{
using (var db = ContextFactory.CreateContext())
{
IOrderedQueryable<Person> sortedList = sorter.Sort(db.Persons);
return sortedList.ToArray();
}
}
And you can create an EntitiySorter
like this:
IEntitySorter<Person> sorter = EntitySorter<Person>
.OrderBy(p => p.Name)
.ThenByDescending(p => p.Id);
Or like this:
var sorter = EntitySorter<Person>
.OrderByDescending("Address.City")
.ThenBy("Id");
this worked for me on Ubuntu 20.04 with mysql 8, the weird hashing thing is because the native PASSWORD() function was removed in mysql 8 (or earlier?)
UPDATE mysql.user SET
plugin = 'mysql_native_password',
Host = '%',
authentication_string = CONCAT('*', UPPER(SHA1(UNHEX(SHA1('insert password here')))))
WHERE User = 'root';
FLUSH PRIVILEGES;
You can not convert to string if your integer value is zero or starts with zero (in which case 1st zero will be neglected). Try change.
int NUM=null;
this is how I fix this issue
1.open my project structure
2.click module
3.click plus button
4.click import module,and find the module's pom
5.make sure you select the module you want to import,then next next finish:)
In the following example you have an PHP array, then firstly create a JavaScript array by a PHP array:
<script type="javascript">
day = new Array(<?php echo implode(',', $day); ?>);
week = new Array(<?php echo implode(',',$week); ?>);
month = new Array(<?php echo implode(',',$month); ?>);
<!-- Then pass it to the JavaScript function: -->
drawChart(<?php echo count($day); ?>, day, week, month);
</script>
Try this:
$(function () {
$('#row_dim').hide(); // this line you can avoid by adding #row_dim{display:none;} in your CSS
$('#type').change(function () {
$('#row_dim').hide();
if (this.options[this.selectedIndex].value == 'parcel') {
$('#row_dim').show();
}
});
});
If you use gcc, there's gprof available.
I wanted to the know how programmer find memory leak
Some uses tools, some does what you do, could also through peer code review
Is there any standard or procedure one should follow to ensure there is no memory leak in the program
For me: whenever I create dynamically allocated objects, I always put the freeing code after, then fill the code between. This would be OK if you're sure there won't be exceptions in the code between. Otherwise, I make use of try-finally (I don't use C++ frequently).
I don't have enough reputation to comment on the relevant answers, but to people reading this; adding .btn does not just add the pointer cursor but adds a lot of other styling as well. Which is great if it's a button and you want the bootstap button styling, but in other cases it would mess a lot up for other elements.
The best thing you can do, like Hari Das suggested, and which I also always do, is to add the following css:
.cursor-pointer {
cursor: pointer;
}
After which you can add it to any element
<div class="cursor-pointer"> .. </div>
I had multiple dataframes with different floating point, so thx to Allans idea made dynamic length.
pd.set_option('display.float_format', lambda x: f'%.{len(str(x%1))-2}f' % x)
The minus of this is that if You have last 0 in float, it will cut it. So it will be not 0.000070, but 0.00007.
/etc/services
is only advisory, it's a listing of well-known ports. It doesn't mean that anything is actually running on that port or that the named service will run on that port.
In PostgreSQL's case it's typical to use port 5432 if it is available. If it isn't, most installers will choose the next free port, usually 5433.
You can see what is actually running using the netstat
tool (available on OS X, Windows, and Linux, with command line syntax varying across all three).
This is further complicated on Mac OS X systems by the horrible mess of different PostgreSQL packages - Apple's ancient version of PostgreSQL built in to the OS, Postgres.app, Homebrew, Macports, the EnterpriseDB installer, etc etc.
What ends up happening is that the user installs Pg and starts a server from one packaging, but uses the psql
and libpq
client from a different packaging. Typically this occurs when they're running Postgres.app or homebrew Pg and connecting with the psql
that shipped with the OS. Not only do these sometimes have different default ports, but the Pg that shipped with Mac OS X has a different default unix socket path, so even if the server is running on the same port it won't be listening to the same unix socket.
Most Mac users work around this by just using tcp/ip with psql -h localhost
. You can also specify a port if required, eg psql -h localhost -p 5433
. You might have multiple PostgreSQL instances running so make sure you're connecting to the right one by using select version()
and SHOW data_directory;
.
You can also specify a unix socket directory; check the unix_socket_directories
setting of the PostgreSQL instance you wish to connect to and specify that with psql -h
, e.g.psql -h /tmp
.
A cleaner solution is to correct your system PATH
so that the psql
and libpq
associated with the PostgreSQL you are actually running is what's found first on the PATH
. The details of that depend on your Mac OS X version and which Pg packages you have installed. I don't use Mac and can't offer much more detail on that side without spending more time than is currently available.
See code example below:
SimpleDateFormat df = new SimpleDateFormat("hh:mm");
String formattedDate = df.format(new Date());
out.println(formattedDate);
Provide your package name separately, it requires a String[]
for package names.
Instead of this:
@ComponentScan("com.my.package.first,com.my.package.second")
Use this:
@ComponentScan({"com.my.package.first","com.my.package.second"})
You can access the index attribute of a df using .index
:
In [277]:
df = pd.DataFrame({'a':np.arange(10), 'b':np.random.randn(10)})
df
Out[277]:
a b
0 0 0.293422
1 1 -1.631018
2 2 0.065344
3 3 -0.417926
4 4 1.925325
5 5 0.167545
6 6 -0.988941
7 7 -0.277446
8 8 1.426912
9 9 -0.114189
In [278]:
df.index
Out[278]:
Int64Index([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], dtype='int64')
for my experience, Ellipsis works only if below two attributes are set.
android:ellipsize="end"
android:singleLine="true"
for the width of textview, wrap_content or match_parent should both be good.
I tried Ninh Pham's solution but it didn't work for me until I tweaked it - see below. Remove contentType and don't encode your json data
$.fn.postJSON = function(url, data) {
return $.ajax({
type: 'POST',
url: url,
data: data,
dataType: 'json'
});
The simplest way is to set the new HTML content using:
document.open();
document.write(newContent);
document.close();
C# compiler have only lambda
arg => arg.MyProperty
for infer type of arg(TModel) an type of arg.MyProperty(TProperty). It's impossible.
If @myInt is zero it means no rows in the table: it would be NULL if never set at all.
COUNT will always return a row, even for no rows in a table.
Edit, Apr 2012: the rules for this are described in my answer here:Does COUNT(*) always return a result?
Your count/assign is correct but could be either way:
select @myInt = COUNT(*) from myTable
set @myInt = (select COUNT(*) from myTable)
However, if you are just looking for the existence of rows, (NOT) EXISTS is more efficient:
IF NOT EXISTS (SELECT * FROM myTable)
If you are trying to load a file which is not in the same directory as your Java class, you've got to use the runtime directory structure rather than the one which appears at design time.
To find out what the runtime directory structure is, check your {root project dir}/target/classes directory. This directory is accessible via the "." URL.
Based on user4284592's answer, the following worked for me:
ClassLoader cl = getClass().getClassLoader();
File file = new File(cl.getResource("./docs/doc.pdf").getFile());
with the following directory structure:
{root dir}/target/classes/docs/doc.pdf
Here's an explanation, so you don't just blindly copy and paste my code:
In the given solution Header is hidden for HomeScreen by- options={{headerShown:false}}
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen name="Home" component={HomeScreen} options={{headerShown:false}}/>
<Stack.Screen name="Details" component={DetailsScreen}/>
</Stack.Navigator>
</NavigationContainer>
The Diff Option only appears if the files are in a folder that is part of a Project.
Than you can actually compare files natively right in Sublime Text.
Navigate to the folder containing them through Open Folder... or in a project Select the two files (ie, by holding Ctrl on Windows or ? on macOS) you want to compare in the sidebar Right click and select the Diff files... option.
Nowadays you can use
try {
String s = CompletableFuture.supplyAsync(() -> br.readLine())
.get(1, TimeUnit.SECONDS);
} catch (TimeoutException e) {
System.out.println("Time out has occurred");
} catch (InterruptedException | ExecutionException e) {
// Handle
}
Create a function with return format yyyy-mm-hh hh:mi:ss.sss
create function fn_retornaFecha (@i_fecha datetime)
returns varchar(23)
as
begin
declare
@w_fecha varchar(23),
@w_anio varchar(4),
@w_mes varchar(2),
@w_dia varchar(2),
@w_hh varchar(2),
@w_nn varchar(2),
@w_ss varchar(2),
@w_sss varchar(3)
select @w_fecha = null
if ltrim(rtrim(@i_fecha)) is not null
begin
select
@w_anio = replicate('0',4-char_length( convert(varchar(4), year(@i_fecha)) )) + convert(varchar(4), year(@i_fecha)),
@w_mes = replicate('0',2-char_length( convert(varchar(2),month(@i_fecha)) )) + convert(varchar(2),month(@i_fecha)),
@w_dia = replicate('0',2-char_length( convert(varchar(2), day(@i_fecha)) )) + convert(varchar(2), day(@i_fecha)) ,
@w_hh = replicate('0',2-char_length( convert(varchar(2),datepart( hh, @i_fecha ) ) )) + convert(varchar(2),datepart( hh, @i_fecha ) ),
@w_nn = replicate('0',2-char_length( convert(varchar(2),datepart( mi, @i_fecha ) ) )) + convert(varchar(2),datepart( mi, @i_fecha ) ),
@w_ss = replicate('0',2-char_length( convert(varchar(2),datepart( ss, @i_fecha ) ) )) + convert(varchar(2),datepart( ss, @i_fecha ) ),
@w_sss = convert(varchar(3),datepart( ms, @i_fecha ) ) + replicate('0',3-DATALENGTH( convert(varchar(3),datepart( ms, @i_fecha ) ) ))
select @w_fecha = @w_anio + '-' + @w_mes + '-' + @w_dia + ' ' + @w_hh + ':' + @w_nn + ':' + @w_ss + '.' + @w_sss
end
return @w_fecha
end
go
Example
select fn_retornaFecha(getdate())
and the result is: 2016-12-21 10:12:50.123
This is really handy, but I wanted a way to show all user objects, not just tables, so I adapted it to use sys.objects instead of sys.tables
SET NOCOUNT ON
DECLARE @AllTables table (DbName sysname,SchemaName sysname, ObjectType char(2), ObjectName sysname)
DECLARE
@SearchDb nvarchar(200)
,@SearchSchema nvarchar(200)
,@SearchObject nvarchar(200)
,@SQL nvarchar(4000)
SET @SearchDb='%'
SET @SearchSchema='%'
SET @SearchObject='%Something%'
SET @SQL='select ''?'' as DbName, s.name as SchemaName, t.type as ObjectType, t.name as ObjectName
from [?].sys.objects t inner join sys.schemas s on t.schema_id=s.schema_id
WHERE t.type in (''FN'',''IF'',''U'',''V'',''P'',''TF'')
AND ''?'' LIKE '''+@SearchDb+'''
AND s.name LIKE '''+@SearchSchema+'''
AND t.name LIKE '''+@SearchObject+''''
INSERT INTO @AllTables (DbName, SchemaName, ObjectType, ObjectName)
EXEC sp_msforeachdb @SQL
SET NOCOUNT OFF
SELECT * FROM @AllTables ORDER BY DbName, SchemaName, ObjectType, ObjectName
if you use fragment u should use
getActivity().onBackPressed();
if you use single activity u can use
finish();
Bootstrapping something fast to chart multiple y-axes sharing an x-axis using @joe-kington's answer:
# d = Pandas Dataframe,
# ys = [ [cols in the same y], [cols in the same y], [cols in the same y], .. ]
def chart(d,ys):
from itertools import cycle
fig, ax = plt.subplots()
axes = [ax]
for y in ys[1:]:
# Twin the x-axis twice to make independent y-axes.
axes.append(ax.twinx())
extra_ys = len(axes[2:])
# Make some space on the right side for the extra y-axes.
if extra_ys>0:
temp = 0.85
if extra_ys<=2:
temp = 0.75
elif extra_ys<=4:
temp = 0.6
if extra_ys>5:
print 'you are being ridiculous'
fig.subplots_adjust(right=temp)
right_additive = (0.98-temp)/float(extra_ys)
# Move the last y-axis spine over to the right by x% of the width of the axes
i = 1.
for ax in axes[2:]:
ax.spines['right'].set_position(('axes', 1.+right_additive*i))
ax.set_frame_on(True)
ax.patch.set_visible(False)
ax.yaxis.set_major_formatter(matplotlib.ticker.OldScalarFormatter())
i +=1.
# To make the border of the right-most axis visible, we need to turn the frame
# on. This hides the other plots, however, so we need to turn its fill off.
cols = []
lines = []
line_styles = cycle(['-','-','-', '--', '-.', ':', '.', ',', 'o', 'v', '^', '<', '>',
'1', '2', '3', '4', 's', 'p', '*', 'h', 'H', '+', 'x', 'D', 'd', '|', '_'])
colors = cycle(matplotlib.rcParams['axes.color_cycle'])
for ax,y in zip(axes,ys):
ls=line_styles.next()
if len(y)==1:
col = y[0]
cols.append(col)
color = colors.next()
lines.append(ax.plot(d[col],linestyle =ls,label = col,color=color))
ax.set_ylabel(col,color=color)
#ax.tick_params(axis='y', colors=color)
ax.spines['right'].set_color(color)
else:
for col in y:
color = colors.next()
lines.append(ax.plot(d[col],linestyle =ls,label = col,color=color))
cols.append(col)
ax.set_ylabel(', '.join(y))
#ax.tick_params(axis='y')
axes[0].set_xlabel(d.index.name)
lns = lines[0]
for l in lines[1:]:
lns +=l
labs = [l.get_label() for l in lns]
axes[0].legend(lns, labs, loc=0)
plt.show()
You need to include the getters and setters for all the fields that have been defined in the model Test
class --
public class Test implements Serializable {
private static final long serialVersionUID = -1764970284520387975L;
public String name;
public Test() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Here is the solution, that I adopted as a combination of some proposed solutions in some other forums.
This way you can reference both css files and other js files in one js file, thus making change next time only in a single place. Please let me know if you have any concerns on it.
I have done following:
declared and executed following code in this file
function getVirtualDirectory() {
var vDir = document.location.pathname.split('/');
return '/' + vDir[1] + '/';
}
function include_jQueryFilesToPage() {
var siteAddress = location.protocol + '//' + document.location.hostname + getVirtualDirectory();
var jqCSSFilePath = siteAddress + 'includes/jQueryCSS/ehrgreen-theme/jquery-ui-1.8.2.custom.css';
var jqCoreFilePath = siteAddress + 'includes/jquery-1.4.1.min.js';
var jqUIFilePath = siteAddress + 'includes/jquery-ui-1.8.2.custom.min.js';
var head = document.getElementsByTagName('head')[0];
// jQuery CSS jnclude
var jqCSS = 'cssIDJQ'; // you could encode the css path itself to generate id.
if (!document.getElementById(jqCSS)) {
var link = document.createElement('link');
link.id = jqCSS;
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = jqCSSFilePath;
link.media = 'all';
head.appendChild(link);
}
// Core jQuery include
var jqc = "coreFileRefIDJQ";
if (!document.getElementById(jqc))
document.write('<scr' + 'ipt type="text/javascript" id="' + jqc + '" src="' + jqCoreFilePath + '"></scr' + 'ipt>');
// jQueryUI include
var jqUI = "uiFileRefIDJQ";
if (!document.getElementById(jqUI))
document.write('<scr' + 'ipt type="text/javascript" id="' + jqUI + '" src="' + jqUIFilePath + '"></scr' + 'ipt>');
}
include_jQueryFilesToPage();
I referenced the above jQueryIncluder.js file in another js or xsl file of my .Net project as following:
<script type="text/javascript" src="~/includes/jQueryIncluder.js"></script>
I hope my effort is appreciated.
Thanks
random functions like borland complier
using namespace std;
int sys_random(int min, int max) {
return (rand() % (max - min+1) + min);
}
void sys_randomize() {
srand(time(0));
}
Internally tar xcvf <filename>
will call the binary gzip
from the PATH
environment variable to decompress the files in the tar
archive. Sometimes third party tools use a custom gzip
binary which is not compatible with the tar
binary.
It is a good idea to check the gzip
binary in your PATH
with which gzip
and make sure that a correct gzip
binary is called.
Here is the same solution than Rukshan but in sass (in order to keep your grid configuration) for special case that don't work with Ross Allen solution (when you can't have a parent div.row)
@mixin make-grid-offset-right($class) {
@for $index from 0 through $grid-columns {
.col-#{$class}-offset-right-#{$index} {
margin-right: percentage(($index / $grid-columns));
}
}
}
@include make-grid-offset-right(xs);
@media (min-width: $screen-sm-min) {
@include make-grid-offset-right(sm);
}
@media (min-width: $screen-md-min) {
@include make-grid-offset-right(md);
}
@media (min-width: $screen-lg-min) {
@include make-grid-offset-right(lg);
}
If you're using Maven, set the <encoding>
explicitly in the compiler plugin's configuration, e.g.
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
You could use GSON, using Gradle Build.gradle :
implementation 'com.google.code.gson:gson:2.8.0'
Then in your code, for example pairs of string/boolean with Kotlin :
val nestedData = HashMap<String,Boolean>()
for (i in 0..29) {
nestedData.put(i.toString(), true)
}
val gson = Gson()
val jsonFromMap = gson.toJson(nestedData)
Adding to SharedPrefs :
val sharedPrefEditor = context.getSharedPreferences(_prefName, Context.MODE_PRIVATE).edit()
sharedPrefEditor.putString("sig_types", jsonFromMap)
sharedPrefEditor.apply()
Now to retrieve data :
val gson = Gson()
val sharedPref: SharedPreferences = context.getSharedPreferences(_prefName, Context.MODE_PRIVATE)
val json = sharedPref.getString("sig_types", "false")
val type = object : TypeToken<Map<String, Boolean>>() {}.type
val map = gson.fromJson(json, type) as LinkedTreeMap<String,Boolean>
for (key in map.keys) {
Log.i("myvalues", key.toString() + map.get(key).toString())
}
The alternate way, that doesn't require RPMs. You need to be root
.
Dependencies
Install the following packages:
apt-get install python-dev build-essential libaio1
Download Instant Client for Linux x86-64
Download the following files from Oracle's download site:
Extract the zip files
Unzip the downloaded zip files to some directory, I'm using:
/opt/ora/
Add environment variables
Create a file in /etc/profile.d/oracle.sh
that includes
export ORACLE_HOME=/opt/ora/instantclient_11_2
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$ORACLE_HOME
Create a file in /etc/ld.so.conf.d/oracle.conf
that includes
/opt/ora/instantclient_11_2
Execute the following command
sudo ldconfig
Note: you may need to reboot to apply settings
Create a symlink
cd $ORACLE_HOME
ln -s libclntsh.so.11.1 libclntsh.so
Install cx_Oracle
python package
You may install using pip
pip install cx_Oracle
Or install manually
Download the cx_Oracle source zip that corresponds with your Python and Oracle version. Then expand the archive, and run from the extracted directory:
python setup.py build
python setup.py install
Here are the steps:
Changing this line:
var doc = new jsPDF('L', 'px', [w, h]);
var doc = new jsPDF('L', 'pt', [w, h]);
To fix the dimensions.
c
can be used on lists (and not only on vectors):
# you have
l1 = list(2, 3)
l2 = list(4)
# you want
list(2, 3, 4)
[[1]]
[1] 2
[[2]]
[1] 3
[[3]]
[1] 4
# you can do
c(l1, l2)
[[1]]
[1] 2
[[2]]
[1] 3
[[3]]
[1] 4
If you have a list of lists, you can do it (perhaps) more comfortably with do.call
, eg:
do.call(c, list(l1, l2))
I know the reason why it is the way it is has already been addressed, but when it comes to "custom" boolean formatting, I've got two extension methods that I can't live without anymore :-)
public static class BoolExtensions
{
public static string ToString(this bool? v, string trueString, string falseString, string nullString="Undefined") {
return v == null ? nullString : v.Value ? trueString : falseString;
}
public static string ToString(this bool v, string trueString, string falseString) {
return ToString(v, trueString, falseString, null);
}
}
Usage is trivial. The following converts various bool values to their Portuguese representations:
string verdadeiro = true.ToString("verdadeiro", "falso");
string falso = false.ToString("verdadeiro", "falso");
bool? v = null;
string nulo = v.ToString("verdadeiro", "falso", "nulo");
Assuming you are running on a *nix platform, use cron
and the php
executable.
EDIT:
There are quite a number of questions asking for "running php without cron" on SO already. Here's one:
Schedule scripts without using CRON
That said, the exec() answer above sounds very promising :)
Extract the package to C:\ from here and install it
Copy the path C:\MinGW\bin
which contains gcc.exe.
go to Control Panel->System->Advanced>Environment variables
, and add or modify PATH. (just concatenate with ';')
Then, open a cmd.exe command prompt
(Windows + R and type cmd, if already opened, please close and open a new one, to get the path change)
change the folder to your file path by cd D:\c code Path
type gcc main.c -o helloworld.o
. It will compile the code. for C++ use g++
7 type ./helloworld
to run the program.
If zlib1.dll is missing, download from here
I don't think this DateTimePicker has been mentioned before:
A WPF DateTimePicker That Works Like the One in Winforms
That one is in VB and has some bugs. I converted it to C# and made a new version with bug fixes.
Note: I used the Calendar control in WPFToolkit so that I could use .NET 3.5 instead of .NET 4. If you are using .NET 4, just remove references to "wpftc" in the XAML.
You can try just putting the image in the source directory. You'd link it by replacing the file path with src="../imagenamehere.fileextension
In your case, j3evn.jpg.
Very simple:
import json
data = json.loads('{"one" : "1", "two" : "2", "three" : "3"}')
print data['two']
Your code is working at my end, i have just tested it. Where are you checking your changes? Use Documents directory path. To get path -
NSLog(@"%@",documentsDirectory);
and copy path from console and then open finder and press Cmd+shift+g and paste path here and then open your file
It depends on what format your image files are in, but for a project here at work I used the tiff2pdf tool in LibTIFF from RemoteSensing.org. Basically just used subprocess to call tiff2pdf.exe with the appropriate argument to read the kind of tiff I had and output the kind of pdf I wanted. If they aren't tiffs you could probably convert them to tiffs using PIL, or maybe find a tool more specific to your image type (or more generic if the images will be diverse) like ReportLab mentioned above.
You may have forgot to remove the semicolon to uncomment that line. For the date.timezone = "US/Central"
line, be sure that there's no semicolon in front of that line.
<select ng-model="option" ng-options="o for o in options">
$scope.option will be equal to 'var1' after change, even you see value="0" in generated html
I'm assuming Windows if you're using WAMP. Composer likely is just using the PHP set in your path: How to access PHP with the Command Line on Windows?
You should be able to change the path to PHP using the same instructions.
Otherwise, composer is just a PHAR file, you can download the PHAR and execute it using any PHP:
C:\full\path\to\php.exe C:\full\path\to\composer.phar install
If you're trying to take advantage of polymorphic behavior, you need to ensure that the methods visible to outside classes (that need polymorphism) have the same signature. That means they need to have the same name, number and order of parameters, as well as the parameter types.
In your case, you might do better to have a generic draw()
method, and rely on the subclasses (Rectangle
, Ellipse
) to implement the draw()
method as what you had been thinking of as "drawEllipse" and "drawRectangle".
Don't hesitate but look into your project files after you have built your project for the first time. Look for a manifest file and choose open with notepad.
Add the line:
Main-Class: package.myMainClassName
Where package
is your package and myClassName
is the class with the main(String[] args)
method.
By default i won't use a guard for this one for me it is more can i enter the route or can i leave it. It is not to share data betweenn them.
If you want to load data before we entered a route just add an resolver to this one this is also part of the Router.
As very basic example:
Resolver
import { Resolve, ActivatedRoute } from "@angular/router";
import { Observable } from "rxjs";
import { Injectable } from "@angular/core";
import { take } from "rxjs/operators";
@Injectable()
export class UserResolver implements Resolve<User> {
constructor(
private userService: UserService,
private route: ActivatedRoute
) {}
resolve(): Observable<firebase.User> {
return this.route.params.pipe(
switchMap((params) => this.userService.fetchUser(params.user_id)),
take(1)
);
}
}
put to the router:
RouterModule.forChild([
{
path: "user/:user_id",
component: MyUserDetailPage,
resolve: {
user: UserResolver
}
}
}]
get the data in our component
ngOnInit() {
const user: firebase.User = this.activatedRoute.snapshot.data.user;
}
The downside on this approach is, he will enter the route first if he get the user data not before, this ensures the data for the user has been loaded and is ready on start of the component, but you will stay on the old page as long the data has been loaded (Loading Animation)
Taken from C# 3.0 Nutshell book, by Joseph Albahari
A ManualResetEvent is a variation on AutoResetEvent. It differs in that it doesn't automatically reset after a thread is let through on a WaitOne call, and so functions like a gate: calling Set opens the gate, allowing any number of threads that WaitOne at the gate through; calling Reset closes the gate, causing, potentially, a queue of waiters to accumulate until its next opened.
One could simulate this functionality with a boolean "gateOpen" field (declared with the volatile keyword) in combination with "spin-sleeping" – repeatedly checking the flag, and then sleeping for a short period of time.
ManualResetEvents are sometimes used to signal that a particular operation is complete, or that a thread's completed initialization and is ready to perform work.
You will have to specify a fixed height, you cannot use 100% because there is nothing for this to be compared to, as in height=100%
of what?
Edited fiddle:
Use:
git checkout -b serverfix origin/serverfix
This is a common enough operation that Git provides the --track
shorthand:
git checkout --track origin/serverfix
In fact, this is so common that there’s even a shortcut for that shortcut. If the branch name you’re trying to checkout (a) doesn’t exist and (b) exactly matches a name on only one remote, Git will create a tracking branch for you:
git checkout serverfix
To set up a local branch with a different name than the remote branch, you can easily use the first version with a different local branch name:
git checkout -b sf origin/serverfix
Now, your local branch sf
will automatically pull from origin/serverfix
.
Source: Pro Git, 2nd Edition, written by Scott Chacon and Ben Straub (cut for readability)
When the text is a number with leading zeros, then do: (Cuando el texto es un número que empieza por ceros, hacer)
$objPHPExcel->getActiveSheet()->setCellValueExplicit('A1', $val,PHPExcel_Cell_DataType::TYPE_STRING);
Apache commons StringUtils class has a join method.
Here's my step in Ubuntu 16.04 and Tomcat 8.
Copy folder /var/lib/tomcat8/webapps/ROOT to your folder.
cp -r /var/lib/tomcat8/webapps/ROOT /var/lib/tomcat8/webapps/{yourfolder}
Add your html, css, js, to your folder.
Open "http://localhost:8080/{yourfolder}" in browser
Notes:
If you using chrome web browser and did wrong folder before, then clean web browser's cache(or change another name) otherwise (sometimes) it always 404.
The folder META-INF with context.xml is needed.
DecimalFormat df = new DecimalFormat("###.##");
double total = Double.valueOf(val);
Here is a simple snippet that sorts a javascript representation of a Json.
function isObject(v) {
return '[object Object]' === Object.prototype.toString.call(v);
};
JSON.sort = function(o) {
if (Array.isArray(o)) {
return o.sort().map(JSON.sort);
} else if (isObject(o)) {
return Object
.keys(o)
.sort()
.reduce(function(a, k) {
a[k] = JSON.sort(o[k]);
return a;
}, {});
}
return o;
}
It can be used as follows:
JSON.sort({
c: {
c3: null,
c1: undefined,
c2: [3, 2, 1, 0],
},
a: 0,
b: 'Fun'
});
That will output:
{
a: 0,
b: 'Fun',
c: {
c2: [3, 2, 1, 0],
c3: null
}
}
I have a feeling that your ClientID
is not of a string type (zero-terminated char*
or std::string
) but some integral type (e.g. int
) so you need to convert number to the string first:
std::stringstream ss;
ss << ClientID;
query.append(ss.str());
But you can use operator+
as well (instead of append
):
query += ss.str();
To understand it in a easier way, following are the diffrences between JSON object and JSON array:
Link to Tabular Difference : https://i.stack.imgur.com/GIqI9.png
JSON Array
1. Arrays in JSON are used to organize a collection of related items
(Which could be JSON objects)
2. Array values must be of type string, number, object, array, boolean or null
3. Syntax:
[ "Ford", "BMW", "Fiat" ]
4. JSON arrays are surrounded by square brackets [].
**Tip to remember** : Here, order of element is important. That means you have
to go straight like the shape of the bracket i.e. straight lines.
(Note :It is just my logic to remember the shape of both.)
5. Order of elements is important. Example: ["Ford","BMW","Fiat"] is not
equal to ["Fiat","BMW","Ford"]
6. JSON can store nested Arrays that are passed as a value.
JSON Object
1. JSON objects are written in key/value pairs.
2. Keys must be strings, and values must be a valid JSON data type (string, number,
object, array, boolean or null).Keys and values are separated by a colon.
Each key/value pair is separated by a comma.
3. Syntax:
{ "name":"Somya", "age":25, "car":null }
4. JSON objects are surrounded by curly braces {}
Tip to remember : Here, order of element is not important. That means you can go
the way you like. Therefore the shape of the braces i.e. wavy.
(Note : It is just my logic to remember the shape of both.)
5. Order of elements is not important.
Example: { rollno: 1, firstname: 'Somya'}
is equal to
{ firstname: 'Somya', rollno: 1}
6. JSON can store nested objects in JSON format in addition to nested arrays.
I wrote this ES6 Class which does the Job.
class SvgToPngConverter {
constructor() {
this._init = this._init.bind(this);
this._cleanUp = this._cleanUp.bind(this);
this.convertFromInput = this.convertFromInput.bind(this);
}
_init() {
this.canvas = document.createElement("canvas");
this.imgPreview = document.createElement("img");
this.imgPreview.style = "position: absolute; top: -9999px";
document.body.appendChild(this.imgPreview);
this.canvasCtx = this.canvas.getContext("2d");
}
_cleanUp() {
document.body.removeChild(this.imgPreview);
}
convertFromInput(input, callback) {
this._init();
let _this = this;
this.imgPreview.onload = function() {
const img = new Image();
_this.canvas.width = _this.imgPreview.clientWidth;
_this.canvas.height = _this.imgPreview.clientHeight;
img.crossOrigin = "anonymous";
img.src = _this.imgPreview.src;
img.onload = function() {
_this.canvasCtx.drawImage(img, 0, 0);
let imgData = _this.canvas.toDataURL("image/png");
if(typeof callback == "function"){
callback(imgData)
}
_this._cleanUp();
};
};
this.imgPreview.src = input;
}
}
Here is how you use it
let input = "https://restcountries.eu/data/afg.svg"
new SvgToPngConverter().convertFromInput(input, function(imgData){
// You now have your png data in base64 (imgData).
// Do what ever you wish with it here.
});
If you want a vanilla JavaScript version, you could head over to Babel website and transpile the code there.
if your world is 100% ascii/utf-8
(a lot of use cases fit in that box):
b = bytearray(s, 'utf-8')
# process - e.g., lowercasing:
# b[0] = b[i+1] - 32
s = str(b, 'utf-8')
python 3.7.3
you can use a stackLayout, inside of this layout you can put a list a frame, for example:
<StackLayout VerticalOptions="FillAndExpand">
<ListView ItemsSource="{Binding YourList}"
CachingStrategy="RecycleElement"
HasUnevenRows="True">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell >
<StackLayout Orientation="Horizontal">
<Label Text="{Binding Image, Mode=TwoWay}" />
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
<Frame BackgroundColor="AliceBlue" HorizontalOptions="FillAndExpand">
<Button Text="More"></Button>
</Frame>
</StackLayout>
this is the result:
create_table :you_table_name do |t| t.references :studant, index: { name: 'name_for_studant_index' } t.references :teacher, index: { name: 'name_for_teacher_index' } end
Another workaround might be to use <div>
of the same size to wrap the <svg>
. After that, you will be able to apply "background-color"
, and "background-image"
that will affect thesvg
.
<div class="background">
<svg></svg>
</div>
<style type="text/css">
.background{
background-color: black;
/*background-image: */
}
</style>
AllDogs.First(d => d.Id == "2").Name = "some value";
However, a safer version of that might be this:
var dog = AllDogs.FirstOrDefault(d => d.Id == "2");
if (dog != null) { dog.Name = "some value"; }
Fast image resize/resample algorithm using Hermite filter with JavaScript. Support transparency, gives good quality. Preview:
Update: version 2.0 added on GitHub (faster, web workers + transferable objects). Finally i got it working!
Git: https://github.com/viliusle/Hermite-resize
Demo: http://viliusle.github.io/miniPaint/
/**
* Hermite resize - fast image resize/resample using Hermite filter. 1 cpu version!
*
* @param {HtmlElement} canvas
* @param {int} width
* @param {int} height
* @param {boolean} resize_canvas if true, canvas will be resized. Optional.
*/
function resample_single(canvas, width, height, resize_canvas) {
var width_source = canvas.width;
var height_source = canvas.height;
width = Math.round(width);
height = Math.round(height);
var ratio_w = width_source / width;
var ratio_h = height_source / height;
var ratio_w_half = Math.ceil(ratio_w / 2);
var ratio_h_half = Math.ceil(ratio_h / 2);
var ctx = canvas.getContext("2d");
var img = ctx.getImageData(0, 0, width_source, height_source);
var img2 = ctx.createImageData(width, height);
var data = img.data;
var data2 = img2.data;
for (var j = 0; j < height; j++) {
for (var i = 0; i < width; i++) {
var x2 = (i + j * width) * 4;
var weight = 0;
var weights = 0;
var weights_alpha = 0;
var gx_r = 0;
var gx_g = 0;
var gx_b = 0;
var gx_a = 0;
var center_y = (j + 0.5) * ratio_h;
var yy_start = Math.floor(j * ratio_h);
var yy_stop = Math.ceil((j + 1) * ratio_h);
for (var yy = yy_start; yy < yy_stop; yy++) {
var dy = Math.abs(center_y - (yy + 0.5)) / ratio_h_half;
var center_x = (i + 0.5) * ratio_w;
var w0 = dy * dy; //pre-calc part of w
var xx_start = Math.floor(i * ratio_w);
var xx_stop = Math.ceil((i + 1) * ratio_w);
for (var xx = xx_start; xx < xx_stop; xx++) {
var dx = Math.abs(center_x - (xx + 0.5)) / ratio_w_half;
var w = Math.sqrt(w0 + dx * dx);
if (w >= 1) {
//pixel too far
continue;
}
//hermite filter
weight = 2 * w * w * w - 3 * w * w + 1;
var pos_x = 4 * (xx + yy * width_source);
//alpha
gx_a += weight * data[pos_x + 3];
weights_alpha += weight;
//colors
if (data[pos_x + 3] < 255)
weight = weight * data[pos_x + 3] / 250;
gx_r += weight * data[pos_x];
gx_g += weight * data[pos_x + 1];
gx_b += weight * data[pos_x + 2];
weights += weight;
}
}
data2[x2] = gx_r / weights;
data2[x2 + 1] = gx_g / weights;
data2[x2 + 2] = gx_b / weights;
data2[x2 + 3] = gx_a / weights_alpha;
}
}
//clear and resize canvas
if (resize_canvas === true) {
canvas.width = width;
canvas.height = height;
} else {
ctx.clearRect(0, 0, width_source, height_source);
}
//draw
ctx.putImageData(img2, 0, 0);
}
I followed several suggestions in this list without success. Finally got it installed on Windows using this method: I extracted the zip file and placed the folders under my python27
folder. In a DOS window, I navigated to the installed root folder from extracting the zip file (python-dateutil-2.6.0
), then issued this command:
.\python setup.py install
Whammo-bammo it all worked.
async
is used for binding to Observables and Promises, but it seems like you're binding to a regular object. You can just remove both async
keywords and it should probably work.
I saw this solution with T-SQL code and PATINDEX. I like it :-)
CREATE Function [fnRemoveNonNumericCharacters](@strText VARCHAR(1000))
RETURNS VARCHAR(1000)
AS
BEGIN
WHILE PATINDEX('%[^0-9]%', @strText) > 0
BEGIN
SET @strText = STUFF(@strText, PATINDEX('%[^0-9]%', @strText), 1, '')
END
RETURN @strText
END
Another way
=IF(SUMPRODUCT(--(NOT(ISERR(SEARCH({"Gingrich","Obama","Romney"},C1)))))>0,"1","")
Also, if you keep a list of values in, say A1 to A3, then you can use
=IF(SUMPRODUCT(--(NOT(ISERR(SEARCH($A$1:$A$3,C1)))))>0,"1","")
The wildcards are not necessary at all in the Search() function, since Search() returns the position of the found string.
You have to call next()
before you can start reading values from the first row. beforeFirst
puts the cursor before the first row, so there's no data to read.
If you are directly working with matplotlib's pyplot (plt) and if you are more familiar with the new-style format string, you can try this:
from matplotlib.ticker import StrMethodFormatter
plt.gca().yaxis.set_major_formatter(StrMethodFormatter('{x:,.0f}')) # No decimal places
plt.gca().yaxis.set_major_formatter(StrMethodFormatter('{x:,.2f}')) # 2 decimal places
From the documentation:
class matplotlib.ticker.StrMethodFormatter(fmt)
Use a new-style format string (as used by str.format()) to format the tick.
The field used for the value must be labeled x and the field used for the position must be labeled pos.
select v.name
from INFORMATION_SCHEMA.VIEWS iv
join sys.views v on v.name = iv.Table_Name
where iv.Table_Catalog = 'Your database name'
This one work for me.I found it myself by combining other answers
private Boolean exit = false;
@override
public void onBackPressed(){
if (exit) {
finish(); // finish activity
}
else {
Toast.makeText(this, "Press Back again to Exit.",
Toast.LENGTH_SHORT).show();
exit = true;
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
Intent a = new Intent(Intent.ACTION_MAIN);
a.addCategory(Intent.CATEGORY_HOME);
a.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(a);
}
}, 1000);
}
Apache has 2 types of MPM (Multi-Processing Modules) defined:
1:Prefork 2: Worker
By default, Apacke is configured in preforked mode i.e. non-threaded pre-forking web server. That means that each Apache child process contains a single thread and handles one request at a time. Because of that, it consumes more resources.
Apache also has the worker MPM that turns Apache into a multi-process, multi-threaded web server. Worker MPM uses multiple child processes with many threads each.
There is a useful difference between call
and start /wait
when calling regsvr32.exe /s
for example, also referenced by Gary in
in his answer to how-do-i-get-the-application-exit-code-from-a-windows-command-line
call regsvr32.exe /s broken.dll
echo %errorlevel%
will always return 0 but
start /wait regsvr32.exe /s broken.dll
echo %errorlevel%
will return the error level from regsvr32.exe
Simplest way (simple collect - supports parallel streams):
public static <T> Stream<T> reverse(Stream<T> stream) {
return stream
.collect(Collector.of(
() -> new ArrayDeque<T>(),
ArrayDeque::addFirst,
(q1, q2) -> { q2.addAll(q1); return q2; })
)
.stream();
}
Advanced way (supports parallel streams in an ongoing way):
public static <T> Stream<T> reverse(Stream<T> stream) {
Objects.requireNonNull(stream, "stream");
class ReverseSpliterator implements Spliterator<T> {
private Spliterator<T> spliterator;
private final Deque<T> deque = new ArrayDeque<>();
private ReverseSpliterator(Spliterator<T> spliterator) {
this.spliterator = spliterator;
}
@Override
@SuppressWarnings({"StatementWithEmptyBody"})
public boolean tryAdvance(Consumer<? super T> action) {
while(spliterator.tryAdvance(deque::addFirst));
if(!deque.isEmpty()) {
action.accept(deque.remove());
return true;
}
return false;
}
@Override
public Spliterator<T> trySplit() {
// After traveling started the spliterator don't contain elements!
Spliterator<T> prev = spliterator.trySplit();
if(prev == null) {
return null;
}
Spliterator<T> me = spliterator;
spliterator = prev;
return new ReverseSpliterator(me);
}
@Override
public long estimateSize() {
return spliterator.estimateSize();
}
@Override
public int characteristics() {
return spliterator.characteristics();
}
@Override
public Comparator<? super T> getComparator() {
Comparator<? super T> comparator = spliterator.getComparator();
return (comparator != null) ? comparator.reversed() : null;
}
@Override
public void forEachRemaining(Consumer<? super T> action) {
// Ensure that tryAdvance is called at least once
if(!deque.isEmpty() || tryAdvance(action)) {
deque.forEach(action);
}
}
}
return StreamSupport.stream(new ReverseSpliterator(stream.spliterator()), stream.isParallel());
}
Note you can quickly extends to other type of streams (IntStream, ...).
Testing:
// Use parallel if you wish only
revert(Stream.of("One", "Two", "Three", "Four", "Five", "Six").parallel())
.forEachOrdered(System.out::println);
Results:
Six
Five
Four
Three
Two
One
Additional notes: The simplest way
it isn't so useful when used with other stream operations (the collect join breaks the parallelism). The advance way
doesn't have that issue, and it keeps also the initial characteristics of the stream, for example SORTED
, and so, it's the way to go to use with other stream operations after the reverse.
It is Purely swift notation an working for me
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
var cellIdentifier:String = "CustomFields"
var cell:CustomCell? = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as? CustomCell
if (cell == nil)
{
var nib:Array = NSBundle.mainBundle().loadNibNamed("CustomCell", owner: self, options: nil)
cell = nib[0] as? CustomCell
}
return cell!
}
The Pandas equivalent to
select * from table where column_name = some_value
is
table[table.column_name == some_value]
Multiple conditions:
table[(table.column_name == some_value) | (table.column_name2 == some_value2)]
or
table.query('column_name == some_value | column_name2 == some_value2')
import pandas as pd
# Create data set
d = {'foo':[100, 111, 222],
'bar':[333, 444, 555]}
df = pd.DataFrame(d)
# Full dataframe:
df
# Shows:
# bar foo
# 0 333 100
# 1 444 111
# 2 555 222
# Output only the row(s) in df where foo is 222:
df[df.foo == 222]
# Shows:
# bar foo
# 2 555 222
In the above code it is the line df[df.foo == 222]
that gives the rows based on the column value, 222
in this case.
Multiple conditions are also possible:
df[(df.foo == 222) | (df.bar == 444)]
# bar foo
# 1 444 111
# 2 555 222
But at that point I would recommend using the query function, since it's less verbose and yields the same result:
df.query('foo == 222 | bar == 444')
I solved it after changing the ssh port & MaxStartups variable in /etc/ssh/sshd_config to ,
port 2244
MaxStartups 100
Then, restart the service
service sshd restart
If still it does not work, restart you system.
Shog9 is right that this doesn't make all that much sense to ask, since an object could be referred to by multiple variables. If you don't really care about that, and all you want is to find the name of one of the global variables that refers to that object, you could do the following hack:
function myClass() {
this.myName = function () {
// search through the global object for a name that resolves to this object
for (var name in this.global)
if (this.global[name] == this)
return name
}
}
// store the global object, which can be referred to as this at the top level, in a
// property on our prototype, so we can refer to it in our object's methods
myClass.prototype.global = this
// create a global variable referring to an object
var myVar = new myClass()
myVar.myName() // returns "myVar"
Note that this is an ugly hack, and should not be used in production code. If there is more than one variable referring to an object, you can't tell which one you'll get. It will only search the global variables, so it won't work if a variable is local to a function. In general, if you need to name something, you should pass the name in to the constructor when you create it.
edit: To respond to your clarification, if you need to be able to refer to something from an event handler, you shouldn't be referring to it by name, but instead add a function that refers to the object directly. Here's a quick example that I whipped up that shows something similar, I think, to what you're trying to do:
function myConstructor () {
this.count = 0
this.clickme = function () {
this.count += 1
alert(this.count)
}
var newDiv = document.createElement("div")
var contents = document.createTextNode("Click me!")
// This is the crucial part. We don't construct an onclick handler by creating a
// string, but instead we pass in a function that does what we want. In order to
// refer to the object, we can't use this directly (since that will refer to the
// div when running event handler), but we create an anonymous function with an
// argument and pass this in as that argument.
newDiv.onclick = (function (obj) {
return function () {
obj.clickme()
}
})(this)
newDiv.appendChild(contents)
document.getElementById("frobnozzle").appendChild(newDiv)
}
window.onload = function () {
var myVar = new myConstructor()
}
I just decided to create the file in D: instead of C: and everything worked well. windows 7...10 have many issues regarding the sharing and authorization of files and folder..
Had the same problem in Eclipse. For some reason I didn't have the servlet.jar file in my build path. What I wound up doing was copying a "lib" folder from another project of mine to the project I was working on, then manually going into that folder and adding the servlet.jar file to the build path (option shows up when you right-click on the file in the project explorer).
basically:
using System.Net;
using System.Net.Http; // in LINQPad, also add a reference to System.Net.Http.dll
WebRequest req = HttpWebRequest.Create("http://google.com");
req.Method = "GET";
string source;
using (StreamReader reader = new StreamReader(req.GetResponse().GetResponseStream()))
{
source = reader.ReadToEnd();
}
Console.WriteLine(source);
By current official documentation there is a short cut that stops and removes containers, networks, volumes, and images created by up, if they are already stopped or partially removed and so on, then it will do the trick too:
docker-compose down
Then if you have new changes on your images or Dockerfiles use:
docker-compose build --no-cache
Finally:docker-compose up
In one command:
docker-compose down && docker-compose build --no-cache && docker-compose up
I was able to test a private method inside using mockito using reflection. Here is the example, tried to name it such that it makes sense
//Service containing the mock method is injected with mockObjects
@InjectMocks
private ServiceContainingPrivateMethod serviceContainingPrivateMethod;
//Using reflection to change accessibility of the private method
Class<?>[] params = new Class<?>[]{PrivateMethodParameterOne.class, PrivateMethodParameterTwo.class};
Method m = serviceContainingPrivateMethod .getClass().getDeclaredMethod("privateMethod", params);
//making private method accessible
m.setAccessible(true);
assertNotNull(m.invoke(serviceContainingPrivateMethod, privateMethodParameterOne, privateMethodParameterTwo).equals(null));
I figured you are using PHP but not mentioned (edited). I found this question by searching internet and since I got solution working , for those who use nodejs here is a simple solution using scan :
var dynamoClient = new AWS.DynamoDB.DocumentClient();
var params = {
TableName: config.dynamoClient.tableName, // give it your table name
Select: "ALL_ATTRIBUTES"
};
dynamoClient.scan(params, function(err, data) {
if (err) {
console.error("Unable to read item. Error JSON:", JSON.stringify(err, null, 2));
} else {
console.log("GetItem succeeded:", JSON.stringify(data, null, 2));
}
});
I assume same code can be translated to PHP too using different AWS SDK
It's simple. Just change the port. Use 3268 instead of 389. If your domain name DOMAIN.LOCAL, in search put DC=DOMAIN,DC=LOCAL
Port 3268: This port is used for queries that are specifically targeted for the global catalog. LDAP requests sent to port 3268 can be used to search objects in the entire forest. However, only the attributes marked for replication to the global catalog can be returned.
Port 389: This port is used for requesting information from the Domain Controller. LDAP requests sent to port 389 can be used to search objects only within the global catalog’s home domain. However, the application can possible to obtain all of the attributes searched objects.
#You can also check it get help for you
if not os.path.isdir('mydir'):
print('new directry has been created')
os.system('mkdir mydir')
As other users have mentioned, enumerate
is a generator that adds an incremental index next to each item of an iterable.
So if you have a list say l = ["test_1", "test_2", "test_3"]
, the list(enumerate(l))
will give you something like this: [(0, 'test_1'), (1, 'test_2'), (2, 'test_3')]
.
Now, when this is useful? A possible use case is when you want to iterate over items, and you want to skip a specific item that you only know its index in the list but not its value (because its value is not known at the time).
for index, value in enumerate(joint_values):
if index == 3:
continue
# Do something with the other `value`
So your code reads better because you could also do a regular for loop with range
but then to access the items you need to index them (i.e., joint_values[i]
).
Although another user mentioned an implementation of enumerate
using zip
, I think a more pure (but slightly more complex) way without using itertools
is the following:
def enumerate(l, start=0):
return zip(range(start, len(l) + start), l)
Example:
l = ["test_1", "test_2", "test_3"]
enumerate(l)
enumerate(l, 10)
Output:
[(0, 'test_1'), (1, 'test_2'), (2, 'test_3')]
[(10, 'test_1'), (11, 'test_2'), (12, 'test_3')]
As mentioned in the comments, this approach with range will not work with arbitrary iterables as the original enumerate
function does.
(typeof files[1] === undefined)?
this.props.upload({file: files}):
this.props.postMultipleUpload({file: files widgetIndex: 0, id})
Check if the second item in the array is undefined using the typeof
and checking for undefined
This can also be achieved with jsp:include. Chad Darby explains well here in this video https://www.youtube.com/watch?v=EWbYj0qoNHo
You might want to look into the DateTime.ToShortTimeString() method.
Also, there many other methods and properties on the DateTime object that can help you in formating the date or time in any way you like. Just take a look at the documentation.
Here is a solution on pure js. You can do it with html5 saveAs. For example this lib could be helpful: https://github.com/eligrey/FileSaver.js
Look at the demo: http://eligrey.com/demos/FileSaver.js/
P.S. There is no information about json save, but you can do it changing file type to "application/json"
and format to .json
If you're just using a vanilla form (not a ModelForm), you can set a Field initial value ( https://docs.djangoproject.com/en/2.2/ref/forms/fields/#django.forms.Field.initial ) like
class MyForm(forms.Form):
my_field = forms.BooleanField(initial=True)
If you're using a ModelForm, you can set a default value on the model field ( https://docs.djangoproject.com/en/2.2/ref/models/fields/#default ), which will apply to the resulting ModelForm, like
class MyModel(models.Model):
my_field = models.BooleanField(default=True)
Finally, if you want to dynamically choose at runtime whether or not your field will be selected by default, you can use the initial parameter to the form when you initialize it:
form = MyForm(initial={'my_field':True})
Reset the file in a correct state, commit, and push again.
If you're sure nobody else has fetched your changes yet, you can use --amend
when committing, to modify your previous commit (i.e. rewrite history), and then push. I think you'll have to use the -f
option when pushing, to force the push, though.
If you need to iterate a queue ... queue isn't the container you need.
Why did you pick a queue?
Why don't you take a container that you can iterate over?
1.if you pick a queue then you say you want to wrap a container into a 'queue' interface: - front - back - push - pop - ...
if you also want to iterate, a queue has an incorrect interface. A queue is an adaptor that provides a restricted subset of the original container
2.The definition of a queue is a FIFO and by definition a FIFO is not iterable
Dirk Eddelbuettel's answer is the best; here I just note that you can get away with not pre-specifying the dataframe dimensions or data types, which is sometimes useful if you have multiple data types and lots of columns:
row1<-list("a",1,FALSE) #use 'list', not 'c' or 'cbind'!
row2<-list("b",2,TRUE)
df<-data.frame(row1,stringsAsFactors = F) #first row
df<-rbind(df,row2) #now this works as you'd expect.
Using sigar should help. Sigar has native hooks to get the stats
new Sigar().getDirStat(dir).getTotal()
In my case, I used a callback in yaxis ticks, my values are in percent and when it reaches 100% it doesn't show the dot, I used this :
yAxes: [{
ticks: {
beginAtZero: true,
steps: 10,
stepValue: 5,
min: 0,
max: 100.1,
callback: function(value, index, values) {
if (value !== 100.1) {
return values[index]
}
}
}
}],
And it worked well.
The closest thing is likely Dav Glass's experimental work using node.js, express and YUI3. Basically, he explains how YUI3 is used to render markup on the server side, then sent to the client where binding to event and data occurs. The beauty is YUI3 is used as-is on both the client and the server. Makes a lot of sense. The one big issue is there is not yet a production ready server-side DOM library.
Added a test page - to color SVG via Filter settings:
E.G
filter: invert(0.5) sepia(1) saturate(5) hue-rotate(175deg)
Upload & Color your SVG - Jsfiddle
Took the idea from: https://blog.union.io/code/2017/08/10/img-svg-fill/
Android changed how permissions work with Android 6.0 that's the reason for your errors. You have to actually request and check if the permission was granted by user to use. So permissions in manifest file will only work for api below 21. Check this link for a snippet of how permissions are requested in api23 http://android-developers.blogspot.nl/2015/09/google-play-services-81-and-android-60.html?m=1
Code:-
If (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) !=
PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSION_RC);
return;
}`
` @Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == STORAGE_PERMISSION_RC) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//permission granted start reading
} else {
Toast.makeText(this, "No permission to read external storage.", Toast.LENGTH_SHORT).show();
}
}
}
}
Perhaps setting both of the buttons layout_width properties to "fill_parent" will do the trick.
I just tested this code and it works in the emulator:
<LinearLayout android:layout_width="fill_parent"
android:layout_height="wrap_content">
<Button android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="hello world"/>
<Button android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="goodbye world"/>
</LinearLayout>
Be sure to set layout_width to "fill_parent" on both buttons.
They are the same.
Both mean that when coming in to the load balancer, the request will be directed to the server that served the first request (and has the session).
The problem has to do with the async attribute in the script tag. The Callback Function is trying to call "initMap()" when it doesn't really exists by the time the request finished.
To solve this I placed the Goole Maps Api Script bellow the script where my initMap function was declared.
Hope this helps
Have you tried to correct the syntax like this?:
create or replace procedure temp_proc AS
begin
DBMS_OUTPUT.PUT_LINE('Test');
end;
@tom-studee you were right, it's possible to do it in the data modeler.
Double click your table, then go to the column section. Here double click on the column which will have the auto increment. In the general section there is a checkbox "autoincrement", just tick it.
After that you can also go to the "autoincrement" section to customize it.
When you save it and ask the data modeler to generate the SQL script, you will see the sequence and trigger which represent your autoincrement.
After years of using XAMPP finally I've given up, and started looking for alternatives. XAMPP has not received any updates for quite a while and it kept breaking down once every two weeks.
The one I've just found and I could absolutely recommend is The Uniform Server
It's really frequently updated, has much more emphasis on security and looks like a much more mature project compared to XAMPP.
They have a wiki where they list all the latest versions of packages. As the time of writing, their newest release is only 4 days old!
Versions in Uniform Server as of today:
Versions in XAMPP as of today:
d = {'key1': 1,'key2': 14,'key3': 47}
sum1 = sum(d[item] for item in d)
print(sum1)
you can do it using the for loop
Possibilities:
Use String.equals()
:
if (some_string.equals("john") ||
some_string.equals("mary") ||
some_string.equals("peter"))
{
}
Use a regular expression:
if (some_string.matches("john|mary|peter"))
{
}
Store a list of strings to be matched against in a Collection and search the collection:
Set<String> names = new HashSet<String>();
names.add("john");
names.add("mary");
names.add("peter");
if (names.contains(some_string))
{
}
Let alone enabling the network adapter under Device Manager may not help. The following helped me resolved the issue.
I tried Disabling and Enabling the Wifi Adapter (i.e. the actual Wifi device adapter not the virtual adapters) in Control Panel -> Network and Internet -> Network Connections altogether worked for me. The same can be done from the Device Manager too. This surely resets the adapter settings and for the Wifi Adapter and the Virtual Miniport adapters.
However, please make sure that the mode is set to allow
as in the below example before you run the start command.
netsh wlan set hostednetwork mode=allow ssid=ssidOfUrChoice key=keyOfUrChoice
and after that run the command netsh wlan start hostednetwork
.
Also once the usage is over with the Miniport adapter connection, it is a good practice to stop it using the following command.
netsh wlan stop hostednetwork
Hope it helps.
In my case Mac OS High Sierra 10.13.6
brew -v
OutPut-
Homebrew 2.2.2
Homebrew/homebrew-core (git revision 71aa; last commit 2020-01-07)
Homebrew/homebrew-cask (git revision 84f00; last commit 2020-01-07)
Where it is documented:
From the API documentation under the has_many association in "Module ActiveRecord::Associations::ClassMethods"
collection.build(attributes = {}, …) Returns one or more new objects of the collection type that have been instantiated with attributes and linked to this object through a foreign key, but have not yet been saved. Note: This only works if an associated object already exists, not if it‘s nil!
The answer to building in the opposite direction is a slightly altered syntax. In your example with the dogs,
Class Dog
has_many :tags
belongs_to :person
end
Class Person
has_many :dogs
end
d = Dog.new
d.build_person(:attributes => "go", :here => "like normal")
or even
t = Tag.new
t.build_dog(:name => "Rover", :breed => "Maltese")
You can also use create_dog to have it saved instantly (much like the corresponding "create" method you can call on the collection)
How is rails smart enough? It's magic (or more accurately, I just don't know, would love to find out!)
glob2rx()
converts a pattern including a wildcard into the equivalent regular expression. You then need to pass this regular expression onto one of R's pattern matching tools.
If you want to match "blue*"
where *
has the usual wildcard, not regular expression, meaning we use glob2rx()
to convert the wildcard pattern into a useful regular expression:
> glob2rx("blue*")
[1] "^blue"
The returned object is a regular expression.
Given your data:
x <- c('red','blue1','blue2', 'red2')
we can pattern match using grep()
or similar tools:
> grx <- glob2rx("blue*")
> grep(grx, x)
[1] 2 3
> grep(grx, x, value = TRUE)
[1] "blue1" "blue2"
> grepl(grx, x)
[1] FALSE TRUE TRUE FALSE
As for the selecting rows problem you posted
> a <- data.frame(x = c('red','blue1','blue2', 'red2'))
> with(a, a[grepl(grx, x), ])
[1] blue1 blue2
Levels: blue1 blue2 red red2
> with(a, a[grep(grx, x), ])
[1] blue1 blue2
Levels: blue1 blue2 red red2
or via subset()
:
> with(a, subset(a, subset = grepl(grx, x)))
x
2 blue1
3 blue2
Hope that explains what grob2rx()
does and how to use it?
I added line under under h3 tag like this
<h3 class="home_title">Your title here</h3>
.home_title{
display:block;
}
.home_title:after {
display:block;
clear:both;
content : "";
position: relative;
left : 0;
bottom : 0;
max-width:250px;
height : 1px;
width : 50%; /* or 100px */
border-bottom:1px solid #e2000f;
margin:0 auto;
padding:4px 0px;
}
How about this:
(my_list and my_list[0]) or None
Note: This should work fine for lists of objects but it might return incorrect answer in case of number or string list per the comments below.
A simplest way that i have tried
You can also create an array in your component file and you can call it with *ngFor directive by returning as an array .
Something like this ....
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-morning',
templateUrl: './morning.component.html',
styleUrls: ['./morning.component.css']
})
export class MorningComponent implements OnInit {
arr = [];
i: number = 0;
arra() {
for (this.i = 0; this.i < 20; this.i++) {
this.arr[this.i]=this.i;
}
return this.arr;
}
constructor() { }
ngOnInit() {
}
}
And this function can be used in your html template file
<p *ngFor="let a of arra(); let i= index">
value:{{a}} position:{{i}}
</p>
A ListView is a specialized ListBox (that is, it inherits from ListBox). It allows you to specify different views rather than a straight list. You can either roll your own view, or use GridView (think explorer-like "details view"). It's basically the multi-column listbox, the cousin of windows form's listview.
If you don't need the additional capabilities of ListView, you can certainly use ListBox if you're simply showing a list of items (Even if the template is complex).
try this one :),
Get-LocalGroup | %{ $groups = "$(Get-LocalGroupMember -Group $_.Name | %{ $_.Name } | Out-String)"; Write-Output "$($_.Name)>`r`n$($groups)`r`n" }
Give the height of the div .youtube-thumb
the height of the image. That should set the problem in Firefox browser.
.youtube-thumb{ height: 106px }
I was also in the same problem, check your build path in eclipse by Right Click on Project > build path > configure build path
Now check for Excluded Files, it should not have your file specified there by any means or by regex.
Cheers!
In my case, the server had been disabled in the domain controller. I went into the COMPUTERS OU in Active directory, right-clicked on the server,enabled it, then did a gpupdate /force from the SQL server. It took a moment, but it finally worked.
Actually this would go faster in most of cases:
SELECT *
FROM table ta1
JOIN table ta2 on ta1.id != ta2.id
WHERE ta1.c2 = ta2.c2 and ta1.c3 = ta2.c3 and ta1.c4 = ta2.c4
You join on different rows which have the same values. I think it should work. Correct me if I'm wrong.
First of all this code snippet
char *addr=NULL;
strcpy(addr,retstring().c_str());
is invalid because you did not allocate memory where you are going to copy retstring().c_str().
As for the error message then it is clear enough. The type of expression data.str().c_str() is const char * but the third parameter of the function is declared as char *. You may not assign an object of type const char * to an object of type char *. Either the function should define the third parameter as const char * if it does not change the object pointed by the third parameter or you may not pass argument of type const char *.
<a href="file://server/directory/file.xlsx" target="_blank">
if I remember correctly.
to allow google translate to be mobile friendly get rid of the layout section, layout: google.translate.TranslateElement.InlineLayout.SIMPLE
<div id="google_translate_element">
</div>
<script type="text/javascript">
function googleTranslateElementInit() {
new google.translate.TranslateElement({pageLanguage: 'en'}, 'google_translate_element');
}
</script>
<script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>
It works on my site and it is mobile friendly. https://livinghisword.org/articles/pages/whoiscernandisourworld.php
You are looking for git merge-base
. Usage:
$ git merge-base branch2 branch3
050dc022f3a65bdc78d97e2b1ac9b595a924c3f2
You need to use HAVING
, not WHERE
.
The difference is: the WHERE
clause filters which rows MySQL selects. Then MySQL groups the rows together and aggregates the numbers for your COUNT
function.
HAVING
is like WHERE
, only it happens after the COUNT
value has been computed, so it'll work as you expect. Rewrite your subquery as:
( -- where that pid is in the set:
SELECT c2.pid -- of pids
FROM Catalog AS c2 -- from catalog
WHERE c2.pid = c1.pid
HAVING COUNT(c2.sid) >= 2)
If you update a submodule and commit to it, you need to go to the containing, or higher level repo and add the change there.
git status
will show something like:
modified:
some/path/to/your/submodule
The fact that the submodule is out of sync can also be seen with
git submodule
the output will show:
+afafaffa232452362634243523 some/path/to/your/submodule
The plus indicates that the your submodule is pointing ahead of where the top repo expects it to point to.
simply add this change:
git add some/path/to/your/submodule
and commit it:
git commit -m "referenced newer version of my submodule"
When you push up your changes, make sure you push up the change in the submodule first and then push the reference change in the outer repo. This way people that update will always be able to successfully run
git submodule update
More info on submodules can be found here http://progit.org/book/ch6-6.html.
You can use this function to convert int
to std::string
after including <sstream>
:
#include <sstream>
string IntToString (int a)
{
stringstream temp;
temp<<a;
return temp.str();
}
Update 2020: I have a new answer that replaces this, now 8-years-old, one: https://stackoverflow.com/a/61177330/278976
On Linux, I tried cpp-netlib, libcurl, curlpp, urdl, boost::asio and considered Qt (but turned it down based on the license). All of these were either incomplete for this use, had sloppy interfaces, had poor documentation, were unmaintained or didn't support https.
Then, at the suggestion of https://stackoverflow.com/a/1012577/278976, I tried POCO. Wow, I wish I had seen this years ago. Here's an example of making an HTTP GET request with POCO:
https://stackoverflow.com/a/26026828/2817595
POCO is free, open source (boost license). And no, I don't have any affiliation with the company; I just really like their interfaces. Great job guys (and gals).
https://pocoproject.org/download.html
Hope this helps someone... it took me three days to try all of these libraries out.
What about the SystemParameters class in PresentationFramework? It has a WorkArea property that seems to be what you are looking for.
But, why won't setting the Window.WindowStartupLocation work? CenterScreen is one of the enum values. Do you have to tweak the centering?
I like Get-Command | Format-List
, or shorter, using aliases for the two and only for powershell.exe
:
gcm powershell | fl
You can find aliases like this:
alias -definition Format-List
Tab completion works with gcm
.
try this ...
$("#txtAreaID").bind("keyup", function(event, ui) {
// Write your code here
});
1.create your subfolder just like followings:
app
----controllers
--------admin
--------home
2.configure your code in app/routes.php
<?php
// index
Route::get('/', 'Home\HomeController@index');
// admin/test
Route::group(
array('prefix' => 'admin'),
function() {
Route::get('test', 'Admin\IndexController@index');
}
);
?>
3.write sth in app/controllers/admin/IndexController.php, eg:
<?php
namespace Admin;
class IndexController extends \BaseController {
public function index()
{
return "admin.home";
}
}
?>
4.access your site,eg:localhost/admin/test you'll see "admin.home" on the page
ps: Please ignore my poor English
Sorry to open an old thread but I'm posting just in case it helps someone. This seems to be the easiest way to do this in Python 3.
from datetime import datetime
Date = str(datetime.now())[:10]
Hour = str(datetime.now())[11:13]
Minute = str(datetime.now())[14:16]
Second = str(datetime.now())[17:19]
Millisecond = str(datetime.now())[20:]
If you need the values as a number just cast them as an int e.g
Hour = int(str(datetime.now())[11:13])
My suggestion for dynamic JQuery Grid are below.
http://reconstrukt.com/ingrid/
https://github.com/mleibman/SlickGrid
http://www.datatables.net/index
Best one is :
DataTables is a plug-in for the jQuery Javascript library. It is a highly flexible tool, based upon the foundations of progressive enhancement, which will add advanced interaction controls to any HTML table.
Variable length pagination
On-the-fly filtering
Multi-column sorting with data type detection
Smart handling of column widths
Display data from almost any data source
DOM, Javascript array, Ajax file and server-side processing (PHP, C#, Perl, Ruby, AIR, Gears etc)
Scrolling options for table viewport
Fully internationalisable
jQuery UI ThemeRoller support
Rock solid - backed by a suite of 2600+ unit tests
Wide variety of plug-ins inc. TableTools, FixedColumns, KeyTable and more
Dynamic creation of tables
Ajax auto loading of data
Custom DOM positioning
Single column filtering
Alternative pagination types
Non-destructive DOM interaction
Sorting column(s) highlighting
Advanced data source options
Extensive plug-in support
Sorting, type detection, API functions, pagination and filtering
Fully themeable by CSS
Solid documentation
110+ pre-built examples
Full support for Adobe AIR
declare @d real
set @d=1.0;
select @d*40000*(192+2)*20000+150000
If you're wondering about functionality, then jQuery's .html()
performs the same intended functionality as .innerHTML
, but it also performs checks for cross-browser compatibility.
For this reason, you can always use jQuery's .html()
instead of .innerHTML
where possible.
db.collection.findOne().sort({age:-1}) //get Max without need for limit(1)
in a Visual Basic Macro you would use
pName = ActiveWorkbook.Path ' the path of the currently active file
wbName = ActiveWorkbook.Name ' the file name of the currently active file
shtName = ActiveSheet.Name ' the name of the currently selected worksheet
The first sheet in a workbook can be referenced by
ActiveWorkbook.Worksheets(1)
so after deleting the [Report] tab you would use
ActiveWorkbook.Worksheets("Report").Delete
shtName = ActiveWorkbook.Worksheets(1).Name
to "work on that sheet later on" you can create a range object like
Dim MySheet as Range
MySheet = ActiveWorkbook.Worksheets(shtName).[A1]
and continue working on MySheet(rowNum, colNum)
etc. ...
shortcut creation of a range object without defining shtName:
Dim MySheet as Range
MySheet = ActiveWorkbook.Worksheets(1).[A1]
If you have renamed anything verify the (Properties/) AssemblyInfo.cs
is correct, as well as the header in the service file.
ServiceName.svc
<%@ ServiceHost Language="C#" Debug="true" Service="Company.Namespace.WcfApp" CodeBehind="WcfApp.svc.cs" %>
Aligning with your namespace in your Service.svc.cs
You could return the value using return JsonConvert.SerializeObject(objName); And send it to the front end
document.write(`<td width='74'><button id='button' type='button' onclick='myfunction(\``+ name + `\`)'>click</button></td>`)
Better to use `` than "". This is a more dynamic answer.
Based on Ray Nicholus's answer :
inputElement.onchange = function(event) {
var fileList = inputElement.files;
//TODO do something with fileList.
}
using this will also work :
inputElement.onchange = function(event) {
var fileList = event.target.files;
//TODO do something with fileList.
}
What I know is one reason when “GC overhead limit exceeded” error is thrown when 2% of the memory is freed after several GC cycles
By this error your JVM is signalling that your application is spending too much time in garbage collection. so the little amount GC was able to clean will be quickly filled again thus forcing GC to restart the cleaning process again.
You should try changing the value of -Xmx
and -Xms
.
This line
mnuActionLanguage.ComboBox.DisplayMember = "Lang.Language";
is wrong. Change it to
mnuActionLanguage.ComboBox.DisplayMember = "Language";
and it will work (even without DataBind()).
You should not rely on [NSDate date]
for timing purposes since it can over- or under-report the elapsed time. There are even cases where your computer will seemingly time-travel since the elapsed time will be negative! (E.g. if the clock moved backwards during timing.)
According to Aria Haghighi in the "Advanced iOS Gesture Recognition" lecture of the Winter 2013 Stanford iOS course (34:00), you should use CACurrentMediaTime()
if you need an accurate time interval.
Objective-C:
#import <QuartzCore/QuartzCore.h>
CFTimeInterval startTime = CACurrentMediaTime();
// perform some action
CFTimeInterval elapsedTime = CACurrentMediaTime() - startTime;
Swift:
let startTime = CACurrentMediaTime()
// perform some action
let elapsedTime = CACurrentMediaTime() - startTime
The reason is that [NSDate date]
syncs on the server, so it could lead to "time-sync hiccups" which can lead to very difficult-to-track bugs. CACurrentMediaTime()
, on the other hand, is a device time that doesn't change with these network syncs.
You will need to add the QuartzCore framework to your target's settings.
Solution based on Ashish answer with Java
private void setUI(){
mainToolbar = findViewById(R.id.mainToolbar);
setSupportActionBar(mainToolbar);
DrawerLayout drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_home, R.id.nav_messaging, R.id.nav_me)
.setDrawerLayout(drawer)
.build();
navController = Navigation.findNavController(this, R.id.nav_host_fragment);
navController.addOnDestinationChangedListener(navDestinationChange);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
}
private NavController.OnDestinationChangedListener navDestinationChange = new NavController.OnDestinationChangedListener(){
@Override
public void onDestinationChanged(@NonNull NavController controller, @NonNull NavDestination destination, @Nullable Bundle arguments) {
if(R.id.nav_home==destination.getId()){
destination.setLabel("News");
}
}
};
Depending on your application, you might want to implement regex matching for the countries where most of your visitors originate and no validation for the rest (accept anything).
scp is best for one file.
OR a combination of tar
& compression for smaller data sets
like source code trees with small resources (ie: images, sqlite etc).
It becomes impractical to build a zip/tar.gz file to transfer with scp at this point do to the physical limits of the hosted server.
As an exercise, you can do some gymnastics like piping tar
into ssh
and redirecting the results into a remote file. (saving the need to build
a swap or temporary clone aka zip or tar.gz)
However,
rsync simplify's this process and allows you to transfer data without consuming any additional disc space.
Also,
Continuous (cron?) updates use minimal changes vs full cloned copies speed up large data migrations over time.
tl;dr
scp
== small scale (with room to build compressed files on the same drive)
rsync
== large scale (with the necessity to backup large data and no room left)
I know this topic is old but I think I can contribute. You can trigger the default behavior of an event on a specific element any time in your handler function if you already know that behavior. For example, when you trigger the click event on the reset button, you actually call the reset function on the closest form as the default behavior. In your handler function, after using the preventDefault function, you can recall the default behavior by calling the reset function on the closest form anywhere in your handler code.
Hy, In my case this error appeared because the Application pool of the webservice had the wrong 32/64 bit setting. So this error needed the following fix: you go to the IIS, select the site of the webservice , go to Advanced setting and get the application pool. Then go to Application pools, select it, go to "Advanced settings..." , select the "Enable 32 bit applications" and make it Enable or Disable, according to the 32/64 bit type of your webservice. If the setting is True, it means that it only allows 32 bit applications, so for 64 bit apps you have to make it "Disable" (default).
For me, this worked:
rawText.replaceAll("(\\\\r\\\\n|\\\\n)", "\\\n");
Tip: use regex tester for quick testing without compiling in your environment
To check if file is empty or has only white spaces, you can use grep:
if [[ -z $(grep '[^[:space:]]' $filename) ]] ; then
echo "Empty file"
...
fi
I use following code for get different result from condition That worked for me.
Select A.column, B.column
FROM TABLE1 A
INNER JOIN
TABLE2 B
ON A.Id = (case when (your condition) then b.Id else (something) END)
JQuery 10.1.2 has a nice show and hide functions that encapsulate the behavior you are talking about. This would save you having to write a new function or keep track of css classes.
$("new").show();
$("new").hide();
IEquatable<T>
can be a much easier way to do this with modern frameworks.
You get a nice simple bool Equals(T other)
function and there's no messing around with casting or creating a separate class.
public class Person : IEquatable<Person>
{
public Person(string name, string hometown)
{
this.Name = name;
this.Hometown = hometown;
}
public string Name { get; set; }
public string Hometown { get; set; }
// can't get much simpler than this!
public bool Equals(Person other)
{
return this.Name == other.Name && this.Hometown == other.Hometown;
}
public override int GetHashCode()
{
return Name.GetHashCode(); // see other links for hashcode guidance
}
}
Note you DO have to implement GetHashCode
if using this in a dictionary or with something like Distinct
.
PS. I don't think any custom Equals methods work with entity framework directly on the database side (I think you know this because you do AsEnumerable) but this is a much simpler method to do a simple Equals for the general case.
If things don't seem to be working (such as duplicate key errors when doing ToDictionary) put a breakpoint inside Equals to make sure it's being hit and make sure you have GetHashCode
defined (with override keyword).
No -P needed; -E is sufficient:
grep -E '(^|\s)abc(\s|$)'
or even without -E:
grep '\(^\|\s\)abc\(\s\|$\)'
Set a height to the last placeholder div.
<div class="row" style="height:30px;">
<!--placeholder to make the whole block has valid auto height-->
I usually construct custom objects in these loops, and then add these objects to an array that I can easily manipulate, sort, export to CSV, etc.:
# Construct an out-array to use for data export
$OutArray = @()
# The computer loop you already have
foreach ($server in $serverlist)
{
# Construct an object
$myobj = "" | Select "computer", "Speed", "Regcheck"
# Fill the object
$myobj.computer = $computer
$myobj.speed = $speed
$myobj.regcheck = $regcheck
# Add the object to the out-array
$outarray += $myobj
# Wipe the object just to be sure
$myobj = $null
}
# After the loop, export the array to CSV
$outarray | export-csv "somefile.csv"
I'm not sure about Tomcat 7, but with Tomcat 6... once you start Tomcat:
By going into the bin directory and starting startup.bat
(win) or startup.sh
(Unix/osx) it will spin up a local instance of the server running usually on port 8080 by default. Then by going to http://localhost:8080/ and seeing that it is running, there is a link to the manager. If that page is not there, you can try loading the manager by going directly to manager/html, and that will load the Host Manager gui.
http://localhost:8080/manager/html
Make sure Tomcat is running first and that 8080 is the right port. These are just the defaults that tomcat usually runs with.
To login you need to edit the conf/tomcat-users.xml, and create a Manager GUI role
<role rolename="manager-gui"/>
and add that to a user
<user username="admin" password="password" roles="manager-gui"/>
Then when you go to Manager GUI app at http://localhost:8080/manager/html it will prompt you for a username/password, which you added to that config file.
The most robust mechanism for listing all classes in a given package is currently ClassGraph, because it handles the widest possible array of classpath specification mechanisms, including the new JPMS module system. (I am the author.)
List<String> classNames;
try (ScanResult scanResult = new ClassGraph().whitelistPackages("my.package")
.enableClassInfo().scan()) {
classNames = scanResult.getAllClasses().getNames();
}
To see the local packages installed in your project including their versions and without their dependencies, run the below command from the project's root directory. In a React native app this would include the react-native package.
npm list --depth 0
Or if you installed them with yarn:
yarn list --depth=0
And to get just a specific package:
npm list react-native --depth 0
yarn list --pattern react-native --depth=0
The @Tim Pietzcker's answer here
(?<=\[)[^]]+(?=\])
is almost the one I've been looking for. But there is one issue that some legacy browsers can fail on positive lookbehind. So I had to made my day by myself :). I manged to write this:
/([^[]+(?=]))/g
Maybe it will help someone.
console.log("this is a [sample] string with [some] special words. [another one]".match(/([^[]+(?=]))/g));
_x000D_
Ran into this error today while trying to use code to delete a folder/files that are living on a Windoze 7 box that's mounted as a share on a Centos server. Got the inappropriate icotl for device error and tried everything that came to mind. Read just about every post on the net related to this.
Obviously the problem was isolated to the mounted Windoze share on the Linux server. Looked at the file permissions on the Windoze box and noted the files had their permissions set to read only.
Changed those, went back to the Linux server and all worked as expected. This may not be the solution for most but hopefully it saves someone some time.
The default conversion from an object to string is "[object Object]"
.
As you are dealing with jQuery objects, you might want to do
alert(whichIsVisible()[0].id);
to print the element's ID.
As mentioned in the comments, you should use the tools included in browsers like Firefox or Chrome to introspect objects by doing console.log(whichIsVisible())
instead of alert
.
Sidenote: IDs should not start with digits.
To make your item consistent with the system look and feel try referencing the system attribute android:attr/selectableItemBackground
in your desired view's background or foreground tag:
<ImageView
...
android:background="?android:attr/selectableItemBackground"
android:foreground="?android:attr/selectableItemBackground"
...
/>
Use both attributes to get desired effect before/after API level 23 respectively.
You can just create your own .white
class and add it to the glyphicon element.
.white, .white a {
color: #fff;
}
<i class="glyphicon glyphicon-home white"></i>
My port number is different. i tried using
ssh localhost -p 8088
this worked for me
after generating XML you can just Replace your XML <Marks>... content here </Marks>
tags with <SubjectMarks>... content here </SubjectMarks>tag
. and pass updated XML to your DB.
Edit: I here explain complete process here.
Your XML Generate Like as below.
<NewDataSet>
<StudentMarks>
<StudentID>1</StudentID>
<CourseID>100</CourseID>
<SubjectCode>MT400</SubjectCode>
<Marks>80</Marks>
</StudentMarks>
<StudentMarks>
<StudentID>1</StudentID>
<CourseID>100</CourseID>
<SubjectCode>MT400</SubjectCode>
<Marks>79</Marks>
</StudentMarks>
<StudentMarks>
<StudentID>1</StudentID>
<CourseID>100</CourseID>
<SubjectCode>MT400</SubjectCode>
<Marks>88</Marks>
</StudentMarks>
</NewDataSet>
Here you can assign XML to string variable like as
string strXML = DataSet.GetXML();
strXML = strXML.Replace ("<Marks>","<SubjectMarks>");
strXML = strXML.Replace ("<Marks/>","<SubjectMarks/>");
and now pass strXML To your DB. Hope it will help for you.
Expanding on what others have said I will give a short example.
If you have a 1D array ...
>>> import numpy as np
>>> x = np.arange(4) # array([0, 1, 2, 3])
>>> x[::-1] # returns a view
Out[1]:
array([3, 2, 1, 0])
But if you are working with a 2D array ...
>>> x = np.arange(10).reshape(2, 5)
>>> x
Out[2]:
array([[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9]])
>>> x[::-1] # returns a view:
Out[3]: array([[5, 6, 7, 8, 9],
[0, 1, 2, 3, 4]])
This does not actually reverse the Matrix.
Should use np.flip to actually reverse the elements
>>> np.flip(x)
Out[4]: array([[9, 8, 7, 6, 5],
[4, 3, 2, 1, 0]])
If you want to print the elements of a matrix one-by-one use flat along with flip
>>> for el in np.flip(x).flat:
>>> print(el, end = ' ')
9 8 7 6 5 4 3 2 1 0
I would use serialize()
or json_encode()
.
While it won't give your the exact result string you want, it would be much easier to encode/store/retrieve/decode later on.
You could also use bc
hour=8
result=$(echo "$hour + 1" | bc)
echo $result
9
I figured it out. I had the arguments in the wrong order. This works:
scp -i mykey.pem somefile.txt [email protected]:/
In a tight loop, it's probably better to avoid regex and hardcode your characters:
const CHARS = new Set("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");
function isAlphanumeric(char) {
return CHARS.has(char);
}
The following should do the trick:
div[class^='myclass'], div[class*=' myclass']{
color: #F00;
}
Edit: Added wildcard (*
) as suggested by David
This is easy to do in xml. Set your top container to be a LinearLayout and set the orientation attribute as you wish. Then inside of that place two linearlayouts that both have "fill parent" on width and height. Finally, set the weigth attribute of those two linearlayouts to 1.
There are several overloads to SelectMany
. One of them allows you to keep trace of any relationship between parent and children while traversing the hierarchy.
Example: suppose you have the following structure: League -> Teams -> Player
.
You can easily return a flat collection of players. However you may lose any reference to the team the player is part of.
Fortunately there is an overload for such purpose:
var teamsAndTheirLeagues =
from helper in leagues.SelectMany
( l => l.Teams
, ( league, team ) => new { league, team } )
where helper.team.Players.Count > 2
&& helper.league.Teams.Count < 10
select new
{ LeagueID = helper.league.ID
, Team = helper.team
};
The previous example is taken from Dan's IK blog. I strongly recommend you take a look at it.
run github that you downloaded, click tools and options symbol(top right), click about github for windows and then open the debug log. under DIAGNOSTICS look for Git Executable Exists:
You can do it calling setRowSelectionInterval :
table.setRowSelectionInterval(0, 0);
to select the first row.
Simple answer: give these two tds a style field.
<tr>
<td>One</td>
<td style="padding-right: 10px">Two</td>
<td>Three</td>
<td>Four</td>
</tr>
Tidy one: use class name
<tr>
<td>One</td>
<td class="more-padding-on-right">Two</td>
<td>Three</td>
<td>Four</td>
</tr>
.more-padding-on-right {
padding-right: 10px;
}
Complex one: using nth-child selector in CSS and specify special padding values for these two, which works in modern browsers.
tr td:nth-child(2) {
padding-right: 10px;
}?
Yes. you can't remember all the shortcuts. You will forget many of them for sure. In this way, you can recall it and get the work done quickly.
Press Ctrl+3
And type whatever the hell you want :) It's a shortcut for shortcuts
For those that might end up here looking for the opposite conversion (from XMLGregorianCalendar
to Date
):
XMLGregorianCalendar xcal = <assume this is initialized>;
java.util.Date dt = xcal.toGregorianCalendar().getTime();
You can check out my bash-based C call tree generator here. It lets you specify one or more C functions for which you want caller and/or called information, or you can specify a set of functions and determine the reachability graph of function calls that connects them... I.e. tell me all the ways main(), foo(), and bar() are connected. It uses graphviz/dot for a graphing engine.
You just need to open pg_hba.conf and sets trust in all methods. That's works for me. Therefore the security is null.
I had the same problem. I tried 'yyyy-mm-dd' format i.e. '2013-26-11' and got rid of this problem...
Also you can try to use
@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)
if you are dealing with jackson with version below 2+ (1.9.5) i tested it, you can easily use this annotation above the class. Not for specified for the attributes, just for class decleration.
This question has relevant answers and link to official Java guidance: Is there a Mutex in Java?