On the contrary, I do think working with list
makes it easy to automate such things.
Here is one solution (I stored your four dataframes in folder temp/
).
filenames <- list.files("temp", pattern="*.csv", full.names=TRUE)
ldf <- lapply(filenames, read.csv)
res <- lapply(ldf, summary)
names(res) <- substr(filenames, 6, 30)
It is important to store the full path for your files (as I did with full.names
), otherwise you have to paste the working directory, e.g.
filenames <- list.files("temp", pattern="*.csv")
paste("temp", filenames, sep="/")
will work too. Note that I used substr
to extract file names while discarding full path.
You can access your summary tables as follows:
> res$`df4.csv`
A B
Min. :0.00 Min. : 1.00
1st Qu.:1.25 1st Qu.: 2.25
Median :3.00 Median : 6.00
Mean :3.50 Mean : 7.00
3rd Qu.:5.50 3rd Qu.:10.50
Max. :8.00 Max. :16.00
If you really want to get individual summary tables, you can extract them afterwards. E.g.,
for (i in 1:length(res))
assign(paste(paste("df", i, sep=""), "summary", sep="."), res[[i]])
A Jmeter Test Plan must have listener to showcase the result of performance test execution.
Listeners capture the response coming back from Server while Jmeter runs and showcase in the form of – tree, tables, graphs and log files.
It also allows you to save the result in a file for future reference. There are many types of listeners Jmeter provides. Some of them are: Summary Report, Aggregate Report, Aggregate Graph, View Results Tree, View Results in Table etc.
Here is the detailed understanding of each parameter in Summary report.
By referring to the figure:
Label: It is the name/URL for the specific HTTP(s) Request. If you have selected “Include group name in label?” option then the name of the Thread Group is applied as the prefix to each label.
Samples: This indicates the number of virtual users per request.
Average: It is the average time taken by all the samples to execute specific label. In our case, the average time for Label 1 is 942 milliseconds & total average time is 584 milliseconds.
Min: The shortest time taken by a sample for specific label. If we look at Min value for Label 1 then, out of 20 samples shortest response time one of the sample had was 584 milliseconds.
Max: The longest time taken by a sample for specific label. If we look at Max value for Label 1 then, out of 20 samples longest response time one of the sample had was 2867 milliseconds.
Std. Dev.: This shows the set of exceptional cases which were deviating from the average value of sample response time. The lesser this value more consistent the data. Standard deviation should be less than or equal to half of the average time for a label.
Error%: Percentage of Failed requests per Label.
Throughput: Throughput is the number of request that are processed per time unit(seconds, minutes, hours) by the server. This time is calculated from the start of first sample to the end of the last sample. Larger throughput is better.
KB/Sec: This indicates the amount of data downloaded from server during the performance test execution. In short, it is the Throughput measured in Kilobytes per second.
For more information: http://www.testingjournals.com/understand-summary-report-jmeter/
A List<T>
is already an IEnumerable<T>
, so you can run LINQ statements directly on your List<T>
variable.
If you don't see the LINQ extension methods like OrderBy()
I'm guessing it's because you don't have a using System.Linq
directive in your source file.
You do need to convert the LINQ expression result back to a List<T>
explicitly, though:
List<Customer> list = ...
list = list.OrderBy(customer => customer.Name).ToList()
All of the replies with readonly
are only suitable when this is a pure TS environment - if it's ever being made into a library then this doesn't actually prevent anything, it just provides warnings for the TS compiler itself.
Static is also not correct - that's adding a method to the Class, not to an instance of the class - so you need to address it directly.
There are several ways to manage this, but the pure TS way is to use a getter
- exactly as you have done already.
The alternative way is to put it in as readonly
, but then use Object.defineProperty
to lock it - this is almost the same thing that is being done via the getter, but you can lock it to have a value, rather than a method to use to get it -
class MyClass {
MY_CONSTANT = 10;
constructor() {
Object.defineProperty(this, "MY_CONSTANT", {value: this.MY_CONSTANT});
}
}
The defaults make it read-only, but check out the docs for more details.
I have added below code to terminate tasks you can use it. You may change the retry numbers.
package com.xxx.test.schedulers;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.apache.log4j.Logger;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.stereotype.Component;
import com.xxx.core.XProvLogger;
@Component
class ContextClosedHandler implements ApplicationListener<ContextClosedEvent> , ApplicationContextAware,BeanPostProcessor{
private ApplicationContext context;
public Logger logger = XProvLogger.getInstance().x;
public void onApplicationEvent(ContextClosedEvent event) {
Map<String, ThreadPoolTaskScheduler> schedulers = context.getBeansOfType(ThreadPoolTaskScheduler.class);
for (ThreadPoolTaskScheduler scheduler : schedulers.values()) {
scheduler.getScheduledExecutor().shutdown();
try {
scheduler.getScheduledExecutor().awaitTermination(20000, TimeUnit.MILLISECONDS);
if(scheduler.getScheduledExecutor().isTerminated() || scheduler.getScheduledExecutor().isShutdown())
logger.info("Scheduler "+scheduler.getThreadNamePrefix() + " has stoped");
else{
logger.info("Scheduler "+scheduler.getThreadNamePrefix() + " has not stoped normally and will be shut down immediately");
scheduler.getScheduledExecutor().shutdownNow();
logger.info("Scheduler "+scheduler.getThreadNamePrefix() + " has shut down immediately");
}
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Map<String, ThreadPoolTaskExecutor> executers = context.getBeansOfType(ThreadPoolTaskExecutor.class);
for (ThreadPoolTaskExecutor executor: executers.values()) {
int retryCount = 0;
while(executor.getActiveCount()>0 && ++retryCount<51){
try {
logger.info("Executer "+executor.getThreadNamePrefix()+" is still working with active " + executor.getActiveCount()+" work. Retry count is "+retryCount);
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if(!(retryCount<51))
logger.info("Executer "+executor.getThreadNamePrefix()+" is still working.Since Retry count exceeded max value "+retryCount+", will be killed immediately");
executor.shutdown();
logger.info("Executer "+executor.getThreadNamePrefix()+" with active " + executor.getActiveCount()+" work has killed");
}
}
@Override
public void setApplicationContext(ApplicationContext context)
throws BeansException {
this.context = context;
}
@Override
public Object postProcessAfterInitialization(Object object, String arg1)
throws BeansException {
return object;
}
@Override
public Object postProcessBeforeInitialization(Object object, String arg1)
throws BeansException {
if(object instanceof ThreadPoolTaskScheduler)
((ThreadPoolTaskScheduler)object).setWaitForTasksToCompleteOnShutdown(true);
if(object instanceof ThreadPoolTaskExecutor)
((ThreadPoolTaskExecutor)object).setWaitForTasksToCompleteOnShutdown(true);
return object;
}
}
SELECT TO_CHAR(NOW(), 'Mon YYYY');
Try adding this code to your config. I had a similar issue once, and this workaround did the trick.
app.config(['$qProvider', function ($qProvider) {
$qProvider.errorOnUnhandledRejections(false);
}]);
You do it exactly as you showed with this line:
get.setHeader("Content-Type", "application/x-zip");
So your header is fine and the problem is some other input to the web service. You'll want to debug that on the server side.
Just to add something to previous answers - When upgrading from MySql 5.6 to MySql 8.0, I followed the steps provided here to make a clean uninstall, yet I got following errors
2019-11-05T07:57:31.359304Z 0 [ERROR] [MY-000077] [Server] /usr/local/Cellar/mysql/8.0.18/bin/mysqld: Error while setting value 'ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION' to 'sql_mode'.
2019-11-05T07:57:31.359330Z 0 [ERROR] [MY-013236] [Server] The designated data directory /usr/local/var/mysql is unusable. You can remove all files that the server added to it.
2019-11-05T07:57:31.359413Z 0 [ERROR] [MY-010119] [Server] Aborting
2019-11-05T07:57:31.359514Z 0 [Note] [MY-010120] [Server] Binlog end
Took me some time to figure it out. Found a clue here: https://discourse.brew.sh/t/clean-removal-of-mysql/2251
So, the key to my problem was removing /usr/local/etc/my.cnf file after uninstall. After that one last step, MySql finally started working.
SQL SERVER 2005:
print upper('hello');
print lower('HELLO');
Great collection of answers, would like to add that you can also do this using the :placeholder-shown
CSS selector. A little cleaner to use IMO, especially if you're already using jQ and have placeholders on your inputs.
if ($('input#cust-descrip').is(':placeholder-shown')) {_x000D_
console.log('Empty');_x000D_
}_x000D_
_x000D_
$('input#cust-descrip').on('blur', '', function(ev) {_x000D_
if (!$('input#cust-descrip').is(':placeholder-shown')) {_x000D_
console.log('Has Text!');_x000D_
}_x000D_
else {_x000D_
console.log('Empty!');_x000D_
}_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<input type="text" class="form-control" id="cust-descrip" autocomplete="off" placeholder="Description">
_x000D_
You can also make use of the :valid
and :invalid
selectors if you have inputs that are required. You can use these selectors if you are using the required attribute on an input.
You should change your code to make use of SqlParameters and adapt your insert statement to the following
string connetionString = "Data Source=UMAIR;Initial Catalog=Air; Trusted_Connection=True;" ;
// [ ] required as your fields contain spaces!!
string insStmt = "insert into Main ([First Name], [Last Name]) values (@firstName,@lastName)";
using (SqlConnection cnn = new SqlConnection(connetionString))
{
cnn.Open();
SqlCommand insCmd = new SqlCommand(insStmt, cnn);
// use sqlParameters to prevent sql injection!
insCmd.Parameters.AddWithValue("@firstName", textbox2.Text);
insCmd.Parameters.AddWithValue("@lastName", textbox3.Text);
int affectedRows = insCmd.ExecuteNonQuery();
MessageBox.Show (affectedRows + " rows inserted!");
}
You can use shorthand syntax as of Twig 1.12.0
{{ foo ?: 'no' }} is the same as {{ foo ? foo : 'no' }}
{{ foo ? 'yes' }} is the same as {{ foo ? 'yes' : '' }}
GIT_CURL_VERBOSE=1 git [clone|fetch]…
should tell you where the problem is. In my case it was due to cURL not supporting PEM certificates when built against NSS, due to that support not being mainline in NSS (#726116 #804215 #402712 and more).
Two ways.
i. You can put it in ApplicationController and add the filters in the controller
class ApplicationController < ActionController::Base def filter_method end end class FirstController < ApplicationController before_filter :filter_method end class SecondController < ApplicationController before_filter :filter_method end
But the problem here is that this method will be added to all the controllers since all of them extend from application controller
ii. Create a parent controller and define it there
class ParentController < ApplicationController def filter_method end end class FirstController < ParentController before_filter :filter_method end class SecondController < ParentController before_filter :filter_method end
I have named it as parent controller but you can come up with a name that fits your situation properly.
You can also define the filter method in a module and include it in the controllers where you need the filter
It isn't clear what you mean by "one operation", but no, there's no operator / framework method that I know of to determine if an item is within a range.
You could of course write an extension-method yourself. For example, here's one that assumes that the interval is closed on both end-points.
public static bool IsBetween<T>(this T item, T start, T end)
{
return Comparer<T>.Default.Compare(item, start) >= 0
&& Comparer<T>.Default.Compare(item, end) <= 0;
}
And then use it as:
bool b = 5.IsBetween(0, 10); // true
The request body is available as byte stream by HttpServletRequest#getInputStream()
:
InputStream body = request.getInputStream();
// ...
Or as character stream by HttpServletRequest#getReader()
:
Reader body = request.getReader();
// ...
Note that you can read it only once. The client ain't going to resend the same request multiple times. Calling getParameter()
and so on will implicitly also read it. If you need to break down parameters later on, you've got to store the body somewhere and process yourself.
I think you should be using "local storage" rather than global variables.
If you are concerned that "local storage" may not be supported in very old browsers, consider using an existing plug-in which checks the availability of "local storage" and uses other methods if it isn't available.
I used http://www.jstorage.info/ and I'm happy with it so far.
Use:
document.querySelector('#elementId:checked').value;
This will return the value of the selected radio button.
Here (this) is a object which contains all features/properties of the dom element. you can see by
console.log(this);
This will display all attributes properties of the dom element with hierarchy. You can manipulate the dom element by this.
Also describe on the below link:-
I was experiencing this issue and it was driving me nuts; I ultimately found the following lying in my POM.xml, which was the cause of the problem:
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
<includes>
<include>**/*.properties</include>
</includes>
</resource>
</resources>
npm ERR! node -v v0.8.0
npm ERR! npm -v 1.1.32
Update your node.js installation.The following commands should do it (from here):
sudo npm cache clean -f
sudo npm install -g n
sudo n stable
Edit: okay, if you really have a good reason to run an ancient version of the software, npm set ca null
will fix the issue. It happened, because built-in npm certificate has expired over the years.
There is a known bug in jQuery 1.6.2 that is triggered by a background image being placed on the body element.
The bug report and patch are:
http://bugs.jquery.com/ticket/9823
https://github.com/jquery/jquery/commit/5c4a9cc001fcd803efa65ff95571c72cbdafbe69
I've also had modernizr trigger this error but since I could work around it I never chased it down.
$number=1200.0000;
str_replace('.00', '',number_format($number, 2, '.', ''));
Output will be: 1200
You can use a checkbox
to simulate onClick with CSS:
input[type=checkbox]:checked + p {
display: none;
}
According to maven website, the last version to support Java 6 is 3.2.5, and 3.3 and up use Java 7. My hunch is that you're using Maven 3.3 or higher, and should either upgrade to Java 7 (and set proper source/target attributes in your pom) or downgrade maven.
Your Code is Fine just you need to place it inside the ready function.
$(document).ready( function() {
$("#cpa-form").submit(function(e){
e.preventDefault();
});
}
In a more general way you can use "INTERVAL". Here some examples:
1) add a day
select sysdate + INTERVAL '1' DAY from dual;
2) add 20 days
select sysdate + INTERVAL '20' DAY from dual;
2) add some minutes
select sysdate + INTERVAL '15' MINUTE from dual;
Just in case you have a preference for how negative numbers are formatted:
p "%x" % -1 #=> "..f"
p -1.to_s(16) #=> "-1"
Please use SQL Server Data Tools from SQL Server Integration Services (Transfer Database Task) as here: https://stackoverflow.com/a/27777823/2127493
I suggest to do 2 things:
Question is old, but it's never too late to answer
$(document).ready(function() {
//prevent paste
var usern_paste = document.getElementById('yourid');
usern_paste.onpaste = e => e.preventDefault();
//prevent copy
var usern_drop = document.getElementById('yourid');
usern_drop.ondrop = e => e.preventDefault();
});
$('#yourid').keypress(function (e) {
var regex = new RegExp("^[a-zA-Z0-9\s]");
var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
if (regex.test(str)) {
return true;
}
e.preventDefault();
return false;
});
Here is my solution for a problem where you want to convert all the letters in a string with position of those letters in English alphabet and return a string of those nos.
https://gist.github.com/bondnotanymore/e0f1dcaacfb782348e74fac8b224769e
Let me know if you want to understand it in detail.I have used the following concepts - List comprehension - Dictionary comprehension
If the below doesn't work:
git config --global push.default current
You should also update your project's local config, as its possible your project has local git configurations:
git config --local push.default current
Removing some unnecessary SQL and then COUNT(*)
will be faster than SQL_CALC_FOUND_ROWS
. Example:
SELECT Person.Id, Person.Name, Job.Description, Card.Number
FROM Person
JOIN Job ON Job.Id = Person.Job_Id
LEFT JOIN Card ON Card.Person_Id = Person.Id
WHERE Job.Name = 'WEB Developer'
ORDER BY Person.Name
Then count without unnecessary part:
SELECT COUNT(*)
FROM Person
JOIN Job ON Job.Id = Person.Job_Id
WHERE Job.Name = 'WEB Developer'
I had challenge with users innocently entering € and some using double quotes to define their content. I tweaked a couple of answers from this page and others to finally define my small little work-around
$products = array($ofDirtyArray);
if($products !=null) {
header("Content-type: application/json");
header('Content-Type: charset=utf-8');
array_walk_recursive($products, function(&$val) {
$val = html_entity_decode(htmlentities($val, ENT_QUOTES, "UTF-8"));
});
echo json_encode($products, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK);
}
I hope it helps someone/someone improves it.
i use this: let instance = <T>{};
it generally works
EDIT 1:
export class EntityCollection<T extends { id: number }>{
mutable: EditableEntity<T>[] = [];
immutable: T[] = [];
edit(index: number) {
this.mutable[index].entity = Object.assign(<T>{}, this.immutable[index]);
}
}
Difficult to give code examples in the comments.
To read the words in the file, you can read the contents of the file, which gets you a string - this is what you were doing before, with the read() method - and then use split() to get the individual words. Split breaks up a String on the delimiter provided, or on whitespace by default. For example,
"the quick brown fox".split()
produces
['the', 'quick', 'brown', 'fox']
Similarly,
fileScan.read().split()
will give you an array of Strings. Hope that helps!
IMO, froadie's simple concatenation is fine for a simple case like you presented. If you want to put together several strings, the string join method seems to be preferred:
the_text = ''.join(['the ', 'quick ', 'brown ', 'fox ', 'jumped ', 'over ', 'the ', 'lazy ', 'dog.'])
Edit: Note that join wants an iterable (e.g. a list) as its single argument.
Note that the fields must be in the same order. If the Primary Key you are referencing is specified as (Application, ID) then your foreign key must reference (Application, ID) and NOT (ID, Application) as they are seen as two different keys.
I don't have Python 2.7 installed, but in Python 3.3 calling Popen
with stdout
set to sys.stdout
worked just fine. Not before I had escaped the backslashes in the path, though.
>>> import subprocess
>>> import sys
>>> p = subprocess.Popen(['powershell.exe', 'C:\\Temp\\test.ps1'], stdout=sys.stdout)
>>> Hello World
_
Here is a variant of the first solution using reduce, in case you like being functional. :)
repls = {'hello' : 'goodbye', 'world' : 'earth'}
s = 'hello, world'
reduce(lambda a, kv: a.replace(*kv), repls.iteritems(), s)
martineau's even better version:
repls = ('hello', 'goodbye'), ('world', 'earth')
s = 'hello, world'
reduce(lambda a, kv: a.replace(*kv), repls, s)
How about maybe something like this?
var condCheck1 = new string[]{"a","b","c"};
var condCheck2 = new string[]{"a","b","c","A2"}
if(!condCheck1.Contains(columnName) && !checkbox.checked)
//statement 1
else if (!condCheck2.Contains(columnName))
//statment 2
If the body of the arrow function is wrapped in curly braces, it is not implicitly returned. Wrap the object in parentheses. It would look something like this.
p => ({ foo: 'bar' })
By wrapping the body in parens, the function will return { foo: 'bar }
.
Hopefully, that solves your problem. If not, I recently wrote an article about Arrow functions which covers it in more detail. I hope you find it useful. Javascript Arrow Functions
In addition to kieran's answer, apparently, modern browsers have an Object.keys
function. In this case, you could do this:
Object.keys(jsonArray).length;
More details in this answer on How to list the properties of a javascript object
For texts in angular template (userType
is property of $scope, like $scope.userType):
<span>
{{userType=='admin' ? 'Edit' : 'Show'}}
</span>
I had to do the same thing and this is what I wrote.I made it more flexible in my case as I had multiple group of check boxes to check.
// param: reqNum number of checkboxes to select
$.fn.checkboxValidate = function(reqNum){
var fields = this.serializeArray();
return (fields.length < reqNum) ? 'invalid' : 'valid';
}
then you can pass this function to check multiple group of checkboxes with multiple rules.
// helper function to create error
function err(msg){
alert("Please select a " + msg + " preference.");
}
$('#reg').submit(function(e){
//needs at lease 2 checkboxes to be selected
if($("input.region, input.music").checkboxValidate(2) == 'invalid'){
err("Region and Music");
}
});
various option are available such as:
Double d= 123.12;
BigDecimal b = new BigDecimal(d, MathContext.DECIMAL64); // b = 123.1200000
b = b.setScale(2, BigDecimal.ROUND_HALF_UP); // b = 123.12
BigDecimal b1 =new BigDecimal(collectionFileData.getAmount(), MathContext.DECIMAL64).setScale(2, BigDecimal.ROUND_HALF_UP) // b1= 123.12
d = (double) Math.round(d * 100) / 100;
BigDecimal b2 = new BigDecimal(d.toString()); // b2= 123.12
I'm going to suggest the non-obvious. There is a fantastic (and often under-used) tool called the Immediate Window in Visual Basic Editor. Basically, you can write out commands in VBA and execute them on the spot, sort of like command prompt. It's perfect for cases like this.
Press ALT+F11 to open VBE, then Control+G to open the Immediate Window. Type the following and hit enter:
for each v in range("K2:K5000") : v.value = "'" & v.value : next
And boom! You are all done. No need to create a macro, declare variables, no need to drag and copy, etc. Close the window and get back to work. The only downfall is to undo it, you need to do it via code since VBA will destroy your undo stack (but that's simple).
Adding another "Same symptoms, but different solution" response, just in case somebody is having the same problem, but none of the common solutions are working.
In my case, I had an app that started development prior to the instruction of asset catalogs and the flexibility in icon naming conventions, but was first submitted to the store after the transition. To resolve the issue I had to:
There is no way to create a file without opening it There is os.mknod("newfile.txt")
(but it requires root privileges on OSX). The system call to create a file is actually open()
with the O_CREAT
flag. So no matter how, you'll always open the file.
So the easiest way to simply create a file without truncating it in case it exists is this:
open(x, 'a').close()
Actually you could omit the .close()
since the refcounting GC of CPython will close it immediately after the open()
statement finished - but it's cleaner to do it explicitely and relying on CPython-specific behaviour is not good either.
In case you want touch
's behaviour (i.e. update the mtime in case the file exists):
import os
def touch(path):
with open(path, 'a'):
os.utime(path, None)
You could extend this to also create any directories in the path that do not exist:
basedir = os.path.dirname(path)
if not os.path.exists(basedir):
os.makedirs(basedir)
Just wanted to mention, that you also may have to set the https_proxy
OS environment variable in case https URLs need to be accessed.
In my case it was not obvious to me and I tried for hours to discover this.
My use case: Win 7, jython-standalone-2.5.3.jar, setuptools installation via ez_setup.py
Just to update Gabe Sechan's answer. If your manifest asks for permissions to READ_CALL_LOG and READ_PHONE_STATE, onReceive will called TWICE. One of which has EXTRA_INCOMING_NUMBER in it and the other doesn't. You have to test which has it and it can occur in any order.
The only selector I see is a[id$="name"]
(all links with id finishing by "name") but it's not as restrictive as it should.
Another option for you is a linked list. You'll need to analyze how your program will use the data structure, if you don't need random access it could be faster than reallocating.
The workaround is, I I save the excel file as excel 97-2003 then it works fine
The java.util.Date/Calendar classes are a mess and should be avoided.
Update: The Joda-Time project is in maintenance mode. The team advises migration to the java.time classes.
Here's your answer using the Joda-Time 2.3 library. Very easy.
As noted in the example code, I suggest you use named time zones wherever possible so that your programming can handle Daylight Saving Time (DST) and other anomalies.
If you had placed a T
in the middle of your string instead of a space, you could skip the first two lines of code, dealing with a formatter to parse the string. The DateTime constructor can take a string in ISO 8601 format.
// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
// import org.joda.time.*;
// import org.joda.time.format.*;
// Parse string as a date-time in UTC (no time zone offset).
DateTimeFormatter formatter = org.joda.time.format.DateTimeFormat.forPattern( "yyyy-MM-dd' 'HH:mm:ss" );
DateTime dateTimeInUTC = formatter.withZoneUTC().parseDateTime( "2011-10-06 03:35:05" );
// Adjust for 13 hour offset from UTC/GMT.
DateTimeZone offsetThirteen = DateTimeZone.forOffsetHours( 13 );
DateTime thirteenDateTime = dateTimeInUTC.toDateTime( offsetThirteen );
// Hard-coded offsets should be avoided. Better to use a desired time zone for handling Daylight Saving Time (DST) and other anomalies.
// Time Zone list… http://joda-time.sourceforge.net/timezones.html
DateTimeZone timeZoneTongatapu = DateTimeZone.forID( "Pacific/Tongatapu" );
DateTime tongatapuDateTime = dateTimeInUTC.toDateTime( timeZoneTongatapu );
Dump those values…
System.out.println( "dateTimeInUTC: " + dateTimeInUTC );
System.out.println( "thirteenDateTime: " + thirteenDateTime );
System.out.println( "tongatapuDateTime: " + tongatapuDateTime );
When run…
dateTimeInUTC: 2011-10-06T03:35:05.000Z
thirteenDateTime: 2011-10-06T16:35:05.000+13:00
tongatapuDateTime: 2011-10-06T16:35:05.000+13:00
I am getting the error (...) javax.naming.NameNotFoundException: greetJndi not bound
This means that nothing is bound to the jndi name greetJndi
, very likely because of a deployment problem given the incredibly low quality of this tutorial (check the server logs). I'll come back on this.
Is there any specific directory structure to deploy in JBoss?
The internal structure of the ejb-jar
is supposed to be like this (using the poor naming conventions and the default package as in the mentioned link):
. +-- greetBean.java +-- greetHome.java +-- greetRemote.java +-- META-INF +-- ejb-jar.xml +-- jboss.xml
But as already mentioned, this tutorial is full of mistakes:
<enterprise-beans>]
<-- HERE) in the ejb-jar.xml
(!)PUBLIC
in the ejb-jar.xml
and jboss.xml
(!!)jboss.xml
is incorrect, it should contain a session
element instead of entity
(!!!)Here is a "fixed" version of the ejb-jar.xml
:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE ejb-jar PUBLIC "-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 2.0//EN" "http://java.sun.com/dtd/ejb-jar_2_0.dtd">
<ejb-jar>
<enterprise-beans>
<session>
<ejb-name>greetBean</ejb-name>
<home>greetHome</home>
<remote>greetRemote</remote>
<ejb-class>greetBean</ejb-class>
<session-type>Stateless</session-type>
<transaction-type>Container</transaction-type>
</session>
</enterprise-beans>
</ejb-jar>
And of the jboss.xml
:
<?xml version="1.0"?>
<!DOCTYPE jboss PUBLIC "-//JBoss//DTD JBOSS 3.2//EN" "http://www.jboss.org/j2ee/dtd/jboss_3_2.dtd">
<jboss>
<enterprise-beans>
<session>
<ejb-name>greetBean</ejb-name>
<jndi-name>greetJndi</jndi-name>
</session>
</enterprise-beans>
</jboss>
After doing these changes and repackaging the ejb-jar, I was able to successfully deploy it:
21:48:06,512 INFO [Ejb3DependenciesDeployer] Encountered deployment AbstractVFSDeploymentContext@5060868{vfszip:/home/pascal/opt/jboss-5.1.0.GA/server/default/deploy/greet.jar/} 21:48:06,534 INFO [EjbDeployer] installing bean: ejb/#greetBean,uid19981448 21:48:06,534 INFO [EjbDeployer] with dependencies: 21:48:06,534 INFO [EjbDeployer] and supplies: 21:48:06,534 INFO [EjbDeployer] jndi:greetJndi 21:48:06,624 INFO [EjbModule] Deploying greetBean 21:48:06,661 WARN [EjbModule] EJB configured to bypass security. Please verify if this is intended. Bean=greetBean Deployment=vfszip:/home/pascal/opt/jboss-5.1.0.GA/server/default/deploy/greet.jar/ 21:48:06,805 INFO [ProxyFactory] Bound EJB Home 'greetBean' to jndi 'greetJndi'
That tutorial needs significant improvement; I'd advise from staying away from roseindia.net.
You can do it in multiple ways:
1. Using greater
as comparison function :
#include <bits/stdc++.h>
using namespace std;
int main()
{
priority_queue<int,vector<int>,greater<int> >pq;
pq.push(1);
pq.push(2);
pq.push(3);
while(!pq.empty())
{
int r = pq.top();
pq.pop();
cout<<r<< " ";
}
return 0;
}
2. Inserting values by changing their sign (using minus (-) for positive number and using plus (+) for negative number :
int main()
{
priority_queue<int>pq2;
pq2.push(-1); //for +1
pq2.push(-2); //for +2
pq2.push(-3); //for +3
pq2.push(4); //for -4
while(!pq2.empty())
{
int r = pq2.top();
pq2.pop();
cout<<-r<<" ";
}
return 0;
}
3. Using custom structure or class :
struct compare
{
bool operator()(const int & a, const int & b)
{
return a>b;
}
};
int main()
{
priority_queue<int,vector<int>,compare> pq;
pq.push(1);
pq.push(2);
pq.push(3);
while(!pq.empty())
{
int r = pq.top();
pq.pop();
cout<<r<<" ";
}
return 0;
}
4. Using custom structure or class you can use priority_queue in any order. Suppose, we want to sort people in descending order according to their salary and if tie then according to their age.
struct people
{
int age,salary;
};
struct compare{
bool operator()(const people & a, const people & b)
{
if(a.salary==b.salary)
{
return a.age>b.age;
}
else
{
return a.salary>b.salary;
}
}
};
int main()
{
priority_queue<people,vector<people>,compare> pq;
people person1,person2,person3;
person1.salary=100;
person1.age = 50;
person2.salary=80;
person2.age = 40;
person3.salary = 100;
person3.age=40;
pq.push(person1);
pq.push(person2);
pq.push(person3);
while(!pq.empty())
{
people r = pq.top();
pq.pop();
cout<<r.salary<<" "<<r.age<<endl;
}
Same result can be obtained by operator overloading :
struct people
{
int age,salary;
bool operator< (const people & p)const
{
if(salary==p.salary)
{
return age>p.age;
}
else
{
return salary>p.salary;
}
}};
In main function :
priority_queue<people> pq;
people person1,person2,person3;
person1.salary=100;
person1.age = 50;
person2.salary=80;
person2.age = 40;
person3.salary = 100;
person3.age=40;
pq.push(person1);
pq.push(person2);
pq.push(person3);
while(!pq.empty())
{
people r = pq.top();
pq.pop();
cout<<r.salary<<" "<<r.age<<endl;
}
A quite efficient and platform independent solution would be using the system property for line separators and the StringBuilder class to build strings:
String separator = System.getProperty("line.separator");
String[] lines = {"Line 1", "Line 2" /*, ... */};
StringBuilder builder = new StringBuilder(lines[0]);
for (int i = 1; i < lines.length(); i++) {
builder.append(separator).append(lines[i]);
}
String multiLine = builder.toString();
An alternative to 'LOAD DATA' is available in which the data will not be moved from your existing source location to hive data warehouse location.
You can use ALTER TABLE command with 'LOCATION' option. Here is below required command
ALTER TABLE table_name ADD PARTITION (date_col='2017-02-07') LOCATION 'hdfs/path/to/location/'
The only condition here is, the location should be a directory instead of file.
Hope this will solve the problem.
This one works for me. You can see this code on AccountController -> Register
var user = new JobUser { UserName = model.Email, Email = model.Email };
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
//add this to add role to user
await UserManager.AddToRoleAsync(user.Id, "Name of your role");
}
but the role name must exist in your AspNetRoles table.
in terminal, type : conda list
to obtain the packages installed using conda.
for the packages that pip
recognizes, type : pip list
There may be some overlap of these lists as pip
may recognize packages installed by conda
(but maybe not the other way around, IDK).
There is a useful source here, including how to update or upgrade packages..
In addition to the above answers here is how you might handle a 500 series response from your api where you receive an error message encoded in json:
function callApi(url) {
return fetch(url)
.then(response => {
if (response.ok) {
return response.json().then(response => ({ response }));
}
return response.json().then(error => ({ error }));
})
;
}
let url = 'http://jsonplaceholder.typicode.com/posts/6';
const { response, error } = callApi(url);
if (response) {
// handle json decoded response
} else {
// handle json decoded 500 series response
}
Another variant is
Assert.assertThat(actual, new Matches(expectedRegex));
Moreover in org.mockito.internal.matchers
there are some other interesting matchers, like StartWith
, Contains
etc.
If you will still use JCrop, you will need only this php functions to crop the file:
$img_src = imagecreatefromjpeg($src);
$img_dest = imagecreatetruecolor($new_w,$new_h);
imagecopyresampled($img_dest,$img_src,0,0,$x,$y,$new_w,$new_h,$w,$h);
imagejpeg($img_dest,$dest);
client side:
jQuery(function($){
$('#target').Jcrop({
onChange: showCoords,
onSelect: showCoords,
onRelease: clearCoords
});
});
var x,y,w,h; //these variables are necessary to crop
function showCoords(c)
{
x = c.x;
y = c.y;
w = c.w;
h = c.h;
};
function clearCoords()
{
x=y=w=h=0;
}
Nitpick:
You don't really escape the %
in the string that specifies the format for the printf()
(and scanf()
) family of functions.
The %
, in the printf()
(and scanf()
) family of functions, starts a conversion specification. One of the rules for conversion specification states that a %
as a conversion specifier (immediately following the %
that started the conversion specification) causes a '%'
character to be written with no argument converted.
The string really has 2 '%'
characters inside (as opposed to escaping characters: "a\bc"
is a string with 3 non null characters; "a%%b"
is a string with 4 non null characters).
You don't have to, but some people like to explicitly initialize all variables (I do too). Especially those who program in a variety of languages, it's just easier to have the rule of always initializing your variables rather than deciding case-by-case/language-by-language.
For instance Java has default values for Boolean, int etc .. C on the other hand doesn't automatically give initial values, whatever happens to be in memory is what you end up with unless you assign a value explicitly yourself.
In your case above, as you discovered, the code works just as well without the initialization, esp since the variable is set in the next line which makes it appear particularly redundant. Sometimes you can combine both of those lines (declaration and initialization - as shown in some of the other posts) and get the best of both approaches, i.e., initialize the your variable with the result of the email1.equals (email2);
operation.
I can suggest another solution (alternative to git-submodules) for your problem - gil (git links) tool
It allows to describe and manage complex git repositories dependencies.
Also it provides a solution to the git recursive submodules dependency problem.
Consider you have the following project dependencies: sample git repository dependency graph
Then you can define .gitlinks
file with repositories relation description:
# Projects
CppBenchmark CppBenchmark https://github.com/chronoxor/CppBenchmark.git master
CppCommon CppCommon https://github.com/chronoxor/CppCommon.git master
CppLogging CppLogging https://github.com/chronoxor/CppLogging.git master
# Modules
Catch2 modules/Catch2 https://github.com/catchorg/Catch2.git master
cpp-optparse modules/cpp-optparse https://github.com/weisslj/cpp-optparse.git master
fmt modules/fmt https://github.com/fmtlib/fmt.git master
HdrHistogram modules/HdrHistogram https://github.com/HdrHistogram/HdrHistogram_c.git master
zlib modules/zlib https://github.com/madler/zlib.git master
# Scripts
build scripts/build https://github.com/chronoxor/CppBuildScripts.git master
cmake scripts/cmake https://github.com/chronoxor/CppCMakeScripts.git master
Each line describe git link in the following format:
Finally you have to update your root sample repository:
# Clone and link all git links dependencies from .gitlinks file
gil clone
gil link
# The same result with a single command
gil update
As the result you'll clone all required projects and link them to each other in a proper way.
If you want to commit all changes in some repository with all changes in child linked repositories you can do it with a single command:
gil commit -a -m "Some big update"
Pull, push commands works in a similar way:
gil pull
gil push
Gil (git links) tool supports the following commands:
usage: gil command arguments
Supported commands:
help - show this help
context - command will show the current git link context of the current directory
clone - clone all repositories that are missed in the current context
link - link all repositories that are missed in the current context
update - clone and link in a single operation
pull - pull all repositories in the current directory
push - push all repositories in the current directory
commit - commit all repositories in the current directory
More about git recursive submodules dependency problem.
Well, what is the data source? Your action could take a few defaulted arguments, i.e.
ActionResult Search(string query, int startIndex, int pageSize) {...}
defaulted in the routes setup so that startIndex is 0 and pageSize is (say) 20:
routes.MapRoute("Search", "Search/{query}/{startIndex}",
new
{
controller = "Home", action = "Search",
startIndex = 0, pageSize = 20
});
To split the feed, you can use LINQ quite easily:
var page = source.Skip(startIndex).Take(pageSize);
(or do a multiplication if you use "pageNumber" rather than "startIndex")
With LINQ-toSQL, EF, etc - this should "compose" down to the database, too.
You should then be able to use action-links to the next page (etc):
<%=Html.ActionLink("next page", "Search", new {
query, startIndex = startIndex + pageSize, pageSize }) %>
The following is a minimal example that will look like the following image.
Start with an empty activity. You will perform the following tasks to add the RecyclerView. All you need to do is copy and paste the code in each section. Later you can customize it to fit your needs.
Make sure the following dependencies are in your app gradle.build
file:
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support:recyclerview-v7:28.0.0'
You can update the version numbers to whatever is the most current. Use compile
rather than implementation
if you are still using Android Studio 2.x.
Add the RecyclerView
to your xml layout.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="@+id/rvAnimals"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
Each row in our RecyclerView
is only going to have a single TextView
. Create a new layout resource file.
recyclerview_row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="10dp">
<TextView
android:id="@+id/tvAnimalName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"/>
</LinearLayout>
The RecyclerView
needs an adapter to populate the views in each row with your data. Create a new java file.
MyRecyclerViewAdapter.java
public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.ViewHolder> {
private List<String> mData;
private LayoutInflater mInflater;
private ItemClickListener mClickListener;
// data is passed into the constructor
MyRecyclerViewAdapter(Context context, List<String> data) {
this.mInflater = LayoutInflater.from(context);
this.mData = data;
}
// inflates the row layout from xml when needed
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.recyclerview_row, parent, false);
return new ViewHolder(view);
}
// binds the data to the TextView in each row
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
String animal = mData.get(position);
holder.myTextView.setText(animal);
}
// total number of rows
@Override
public int getItemCount() {
return mData.size();
}
// stores and recycles views as they are scrolled off screen
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView myTextView;
ViewHolder(View itemView) {
super(itemView);
myTextView = itemView.findViewById(R.id.tvAnimalName);
itemView.setOnClickListener(this);
}
@Override
public void onClick(View view) {
if (mClickListener != null) mClickListener.onItemClick(view, getAdapterPosition());
}
}
// convenience method for getting data at click position
String getItem(int id) {
return mData.get(id);
}
// allows clicks events to be caught
void setClickListener(ItemClickListener itemClickListener) {
this.mClickListener = itemClickListener;
}
// parent activity will implement this method to respond to click events
public interface ItemClickListener {
void onItemClick(View view, int position);
}
}
Notes
ListViews
and is a common need. You can remove this code if you don't need it.Add the following code to your main activity.
MainActivity.java
public class MainActivity extends AppCompatActivity implements MyRecyclerViewAdapter.ItemClickListener {
MyRecyclerViewAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// data to populate the RecyclerView with
ArrayList<String> animalNames = new ArrayList<>();
animalNames.add("Horse");
animalNames.add("Cow");
animalNames.add("Camel");
animalNames.add("Sheep");
animalNames.add("Goat");
// set up the RecyclerView
RecyclerView recyclerView = findViewById(R.id.rvAnimals);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
adapter = new MyRecyclerViewAdapter(this, animalNames);
adapter.setClickListener(this);
recyclerView.setAdapter(adapter);
}
@Override
public void onItemClick(View view, int position) {
Toast.makeText(this, "You clicked " + adapter.getItem(position) + " on row number " + position, Toast.LENGTH_SHORT).show();
}
}
Notes
ItemClickListener
that we defined in our adapter. This allows us to handle row click events in onItemClick
.That's it. You should be able to run your project now and get something similar to the image at the top.
Adding a divider between rows
You can add a simple divider like this
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(recyclerView.getContext(),
layoutManager.getOrientation());
recyclerView.addItemDecoration(dividerItemDecoration);
If you want something a little more complex, see the following answers:
Changing row color on click
See this answer for how to change the background color and add the Ripple Effect when a row is clicked.
Updating rows
See this answer for how to add, remove, and update rows.
PDO driver for PostgreSQL is now included in the debian package php5-dev. The above steps using Pecl no longer works.
Depending on what version of React you are using, you may need to use something like this. I know Facebook is thinking about deprecating string refs in the somewhat near future.
var Hello = React.createClass({
componentDidMount: function() {
ReactDOM.findDOMNode(this.test).setAttribute('custom-attribute', 'some value');
},
render: function() {
return <div>
<span ref={(ref) => this.test = ref}>Element with a custom attribute</span>
</div>;
}
});
React.render(<Hello />, document.getElementById('container'));
For those finding this via Google;
I was getting this error because, as suggested by the error, I failed to close a SqlDataReader prior to creating another on the same SqlCommand, mistakenly assuming that it would be garbage collected when leaving the method it was created in.
I solved the issue by calling sqlDataReader.Close();
before creating the second reader.
Though the answer is accepted, but I'm going to answer it anyway.
From the points perspective, it might seem that it's a lot of work. But it's very simple. And Up un till now it has worked on all the devices I have tried with.
At first download the universal ADB driver. Then follow the process below:
Next, select the properties of the device. Then-
Then re-run your app from the android studio. And it will show your device under Choose Device. Cheers!
Sometimes the spring config xml file works not well on next eclipse open up.
It shows error in the xml file caused by schema definition, no matter reopen eclipse or clean up project are both not working.
But try this!
Right click on the spring config xml file, and select
validate
.
After a while, the error disappears and eclipse tells you there is no error on this file.
What a joke...
Chrome browser considers integer value as return type not boolean value so,
this.state.data.sort((a, b) => a.item.timeM > b.item.timeM ? 1:-1).map(
(item, i) => <div key={i}> {item.matchID} {item.timeM} {item.description}</div>
)
Try This
String matchString="ID0001"//assuming we have to find rows having key=ID0001
DataTable dtTarget = new DataTable();
dtTarget = dtSource.Clone();
DataRow[] rowsToCopy;
rowsToCopy = dtSource.Select("key='" + matchString + "'");
foreach (DataRow temp in rowsToCopy)
{
dtTarget.ImportRow(temp);
}
It appears that at least one of your predictors ,x1
, x2
, or x3
, has only one factor level and hence is a constant.
Have a look at
lapply(dataframe.df[c("x1", "x2", "x3")], unique)
to find the different values.
The const with the int on either sides will make pointer to constant int:
const int *ptr=&i;
or:
int const *ptr=&i;
const
after *
will make constant pointer to int:
int *const ptr=&i;
In this case all of these are pointer to constant integer, but none of these are constant pointer:
const int *ptr1=&i, *ptr2=&j;
In this case all are pointer to constant integer and ptr2 is constant pointer to constant integer. But ptr1 is not constant pointer:
int const *ptr1=&i, *const ptr2=&j;
Because I never found a solution to this I decided to upgrade my LAMP environment. I went to Ubuntu 10.4 LTS with PHP 5.3.x. This seems to have stopped the problem for me.
Are you sure that you are executing the script against the correct database? In SQL Server Management studio you can change the database you are running the query against in a drop-down box on one of the toolbars, or you can start your query with this:
USE SomeDatabase
If you just want to know the number, rather than get it in a query then you can use:
SHOW CREATE TABLE tablename;
You should see the auto_increment at the bottom
and if :wq doesn't work like my case use ctrl+z for abort and quit but these will probably make multiple backup file to work with later – Adeem Jan 19 at 9:14
Also be sure to run Git as Administrator! Otherwise the file won't be saved (in my case).
To get the value equivalent to your C cast, just bitwise and with the appropriate mask. e.g. if unsigned long
is 32 bit:
>>> i = -6884376
>>> i & 0xffffffff
4288082920
or if it is 64 bit:
>>> i & 0xffffffffffffffff
18446744073702667240
Do be aware though that although that gives you the value you would have in C, it is still a signed value, so any subsequent calculations may give a negative result and you'll have to continue to apply the mask to simulate a 32 or 64 bit calculation.
This works because although Python looks like it stores all numbers as sign and magnitude, the bitwise operations are defined as working on two's complement values. C stores integers in twos complement but with a fixed number of bits. Python bitwise operators act on twos complement values but as though they had an infinite number of bits: for positive numbers they extend leftwards to infinity with zeros, but negative numbers extend left with ones. The &
operator will change that leftward string of ones into zeros and leave you with just the bits that would have fit into the C value.
Displaying the values in hex may make this clearer (and I rewrote to string of f's as an expression to show we are interested in either 32 or 64 bits):
>>> hex(i)
'-0x690c18'
>>> hex (i & ((1 << 32) - 1))
'0xff96f3e8'
>>> hex (i & ((1 << 64) - 1)
'0xffffffffff96f3e8L'
For a 32 bit value in C, positive numbers go up to 2147483647 (0x7fffffff), and negative numbers have the top bit set going from -1 (0xffffffff) down to -2147483648 (0x80000000). For values that fit entirely in the mask, we can reverse the process in Python by using a smaller mask to remove the sign bit and then subtracting the sign bit:
>>> u = i & ((1 << 32) - 1)
>>> (u & ((1 << 31) - 1)) - (u & (1 << 31))
-6884376
Or for the 64 bit version:
>>> u = 18446744073702667240
>>> (u & ((1 << 63) - 1)) - (u & (1 << 63))
-6884376
This inverse process will leave the value unchanged if the sign bit is 0, but obviously it isn't a true inverse because if you started with a value that wouldn't fit within the mask size then those bits are gone.
Sorry to be late to the party but just found this solution to the problem.
The lines are truncated because ps insists on using the value of $COLUMNS, even if the output is not the screen at that moment. Which is a bug, IMHO. But easy to work around, just make ps think you have a superwide screen, i.e. set COLUMNS high for the duration of the ps command. An example:
$ ps -edalf # truncates lines to screen width
$ COLUMNS=1000 ps -edalf # wraps lines regardless of screen width
I hope this is still useful to someone. All the other ideas seemed much too complicated :)
Here is snippet that allowed me to log out programmatically from facebook. Let me know if you see anything that I might need to improve.
private void logout(){
// clear any user information
mApp.clearUserPrefs();
// find the active session which can only be facebook in my app
Session session = Session.getActiveSession();
// run the closeAndClearTokenInformation which does the following
// DOCS : Closes the local in-memory Session object and clears any persistent
// cache related to the Session.
session.closeAndClearTokenInformation();
// return the user to the login screen
startActivity(new Intent(getApplicationContext(), LoginActivity.class));
// make sure the user can not access the page after he/she is logged out
// clear the activity stack
finish();
}
This will give dead on alignment
input[type="radio"] {
margin-top: 1px;
vertical-align: top;
}
Events are pretty easy in C#, but the MSDN docs in my opinion make them pretty confusing. Normally, most documentation you see discusses making a class inherit from the EventArgs
base class and there's a reason for that. However, it's not the simplest way to make events, and for someone wanting something quick and easy, and in a time crunch, using the Action
type is your ticket.
1. Create your event on your class right after your class
declaration.
public event Action<string,string,string,string>MyEvent;
2. Create your event handler class method in your class.
private void MyEventHandler(string s1,string s2,string s3,string s4)
{
Console.WriteLine("{0} {1} {2} {3}",s1,s2,s3,s4);
}
3. Now when your class is invoked, tell it to connect the event to your new event handler. The reason the +=
operator is used is because you are appending your particular event handler to the event. You can actually do this with multiple separate event handlers, and when an event is raised, each event handler will operate in the sequence in which you added them.
class Example
{
public Example() // I'm a C# style class constructor
{
MyEvent += new Action<string,string,string,string>(MyEventHandler);
}
}
4. Now, when you're ready, trigger (aka raise) the event somewhere in your class code like so:
MyEvent("wow","this","is","cool");
The end result when you run this is that the console will emit "wow this is cool". And if you changed "cool" with a date or a sequence, and ran this event trigger multiple times, you'd see the result come out in a FIFO sequence like events should normally operate.
In this example, I passed 4 strings. But you could change those to any kind of acceptable type, or used more or less types, or even remove the <...>
out and pass nothing to your event handler.
And, again, if you had multiple custom event handlers, and subscribed them all to your event with the +=
operator, then your event trigger would have called them all in sequence.
But what if you want to identify the caller to this event in your event handler? This is useful if you want an event handler that reacts with conditions based on who's raised/triggered the event. There are a few ways to do this. Below are examples that are shown in order by how fast they operate:
Option 1. (Fastest) If you already know it, then pass the name as a literal string to the event handler when you trigger it.
Option 2. (Somewhat Fast) Add this into your class and call it from the calling method, and then pass that string to the event handler when you trigger it:
private static string GetCaller([System.Runtime.CompilerServices.CallerMemberName] string s = null) => s;
Option 3. (Least Fast But Still Fast) In your event handler when you trigger it, get the calling method name string with this:
string callingMethod = new System.Diagnostics.StackTrace().GetFrame(1).GetMethod().ReflectedType.Name.Split('<', '>')[1];
You may have a scenario where your custom event has multiple event handlers, but you want to remove one special one out of the list of event handlers. To do so, use the -=
operator like so:
MyEvent -= MyEventHandler;
A word of minor caution with this, however. If you do this and that event no longer has any event handlers, and you trigger that event again, it will throw an exception. (Exceptions, of course, you can trap with try/catch blocks.)
Okay, let's say you're through with events and you don't want to process any more. Just set it to null like so:
MyEvent = null;
The same caution for Unsubscribing events is here, as well. If your custom event handler no longer has any events, and you trigger it again, your program will throw an exception.
Also, this might help finding the actual location the btsnoop_hci.log is being saved:
adb shell "cat /etc/bluetooth/bt_stack.conf | grep FileName"
You probably have some other "Date" class imported somewhere (or you have a Date class in you package, which does not need to be imported). With "import java.util.*" you are using the "other" Date. In this case it's best to explicitly specify java.util.Date in the code.
Or better, try to avoid naming your classes "Date".
@HostListener
is a decorator for the callback/event handler method, so remove the ;
at the end of this line:
@HostListener('click', ['$event.target']);
Here's a working plunker that I generated by copying the code from the API docs, but I put the onClick()
method on the same line for clarity:
import {Component, HostListener, Directive} from 'angular2/core';
@Directive({selector: 'button[counting]'})
class CountClicks {
numberOfClicks = 0;
@HostListener('click', ['$event.target']) onClick(btn) {
console.log("button", btn, "number of clicks:", this.numberOfClicks++);
}
}
@Component({
selector: 'my-app',
template: `<button counting>Increment</button>`,
directives: [CountClicks]
})
export class AppComponent {
constructor() { console.clear(); }
}
Host binding can also be used to listen to global events:
To listen to global events, a target must be added to the event name. The target can be window, document or body (reference)
@HostListener('document:keyup', ['$event'])
handleKeyboardEvent(kbdEvent: KeyboardEvent) { ... }
Quick example using company1
from your question, with python3.
import pickle
# Save the file
pickle.dump(company1, file = open("company1.pickle", "wb"))
# Reload the file
company1_reloaded = pickle.load(open("company1.pickle", "rb"))
However, as this answer noted, pickle often fails. So you should really use dill
.
import dill
# Save the file
dill.dump(company1, file = open("company1.pickle", "wb"))
# Reload the file
company1_reloaded = dill.load(open("company1.pickle", "rb"))
Google recommend that you don't use any of them, source.
There is no need to use entity references like
&mdash
,&rdquo
, or☺
, assuming the same encoding (UTF-8) is used for files and editors as well as among teams.
Is there a reason you can't simply use "
?
You need to take out a float: left; property... because when you use float the parent div do not grub the height of it's children... If you want the parent dive to get the children height you need to give to the parent div a css property overflow:hidden; But to solve your problem you can use display: table-cell; instead of float... it will automatically scale the div height to its parent height...
You probably want the next transformation for you pixels:
pixels = map(list, image.getdata())
You can't use PHP in the WordPress back-end Page editor. Maybe with a plugin you can, but not out of the box.
The easiest solution for this is creating a shortcode. Then you can use something like this
function input_func( $atts ) {
extract( shortcode_atts( array(
'type' => 'text',
'name' => '',
), $atts ) );
return '<input name="' . $name . '" id="' . $name . '" value="' . (isset($_GET\['from'\]) && $_GET\['from'\] ? $_GET\['from'\] : '') . '" type="' . $type . '" />';
}
add_shortcode( 'input', 'input_func' );
See the Shortcode_API.
The easiest way is
find . | grep test
here find will list all the files in the (.) ie current directory, recursively. And then it is just a simple grep. all the files which name has "test" will appeared.
you can play with grep as per your requirement. Note : As the grep is generic string classification, It can result in giving you not only file names. but if a path has a directory ('/xyz_test_123/other.txt') would also comes to the result set. cheers
For me, the only way on SQL 2008 R2 was this :
EXEC sp_configure 'Show Advanced Options', 1
RECONFIGURE **WITH OVERRIDE**
EXEC sp_configure 'xp_cmdshell', 1
RECONFIGURE **WITH OVERRIDE**
You can do it by hmset
(multiple keys can be set using hmset
).
hmset("RedisKey", dictionaryToSet)
import redis
conn = redis.Redis('localhost')
user = {"Name":"Pradeep", "Company":"SCTL", "Address":"Mumbai", "Location":"RCP"}
conn.hmset("pythonDict", user)
conn.hgetall("pythonDict")
{'Company': 'SCTL', 'Address': 'Mumbai', 'Location': 'RCP', 'Name': 'Pradeep'}
I think these could be helpful for you .
Using a SELECT
statement with a simple CASE
expression
Within a SELECT
statement, a simple CASE
expression allows for only an equality check; no other comparisons are made. The following example uses the CASE
expression to change the display of product line categories to make them more understandable.
USE AdventureWorks2012;
GO
SELECT ProductNumber, Category =
CASE ProductLine
WHEN 'R' THEN 'Road'
WHEN 'M' THEN 'Mountain'
WHEN 'T' THEN 'Touring'
WHEN 'S' THEN 'Other sale items'
ELSE 'Not for sale'
END,
Name
FROM Production.Product
ORDER BY ProductNumber;
GO
Using a SELECT
statement with a searched CASE
expression
Within a SELECT
statement, the searched CASE
expression allows for values to be replaced in the result set based on comparison values. The following example displays the list price as a text comment based on the price range for a product.
USE AdventureWorks2012;
GO
SELECT ProductNumber, Name, "Price Range" =
CASE
WHEN ListPrice = 0 THEN 'Mfg item - not for resale'
WHEN ListPrice < 50 THEN 'Under $50'
WHEN ListPrice >= 50 and ListPrice < 250 THEN 'Under $250'
WHEN ListPrice >= 250 and ListPrice < 1000 THEN 'Under $1000'
ELSE 'Over $1000'
END
FROM Production.Product
ORDER BY ProductNumber ;
GO
Using CASE
in an ORDER BY
clause
The following examples uses the CASE
expression in an ORDER BY
clause to determine the sort order of the rows based on a given column value. In the first example, the value in the SalariedFlag column of the HumanResources.Employee table is evaluated. Employees that have the SalariedFlag set to 1 are returned in order by the BusinessEntityID in descending order. Employees that have the SalariedFlag set to 0 are returned in order by the BusinessEntityID in ascending order. In the second example, the result set is ordered by the column TerritoryName when the column CountryRegionName is equal to 'United States' and by CountryRegionName for all other rows.
SELECT BusinessEntityID, SalariedFlag
FROM HumanResources.Employee
ORDER BY CASE SalariedFlag WHEN 1 THEN BusinessEntityID END DESC
,CASE WHEN SalariedFlag = 0 THEN BusinessEntityID END;
GO
SELECT BusinessEntityID, LastName, TerritoryName, CountryRegionName
FROM Sales.vSalesPerson
WHERE TerritoryName IS NOT NULL
ORDER BY CASE CountryRegionName WHEN 'United States' THEN TerritoryName
ELSE CountryRegionName END;
Using CASE
in an UPDATE
statement
The following example uses the CASE
expression in an UPDATE
statement to determine the value that is set for the column VacationHours for employees with SalariedFlag set to 0. When subtracting 10 hours from VacationHours results in a negative value, VacationHours is increased by 40 hours; otherwise, VacationHours is increased by 20 hours. The OUTPUT
clause is used to display the before and after vacation values.
USE AdventureWorks2012;
GO
UPDATE HumanResources.Employee
SET VacationHours =
( CASE
WHEN ((VacationHours - 10.00) < 0) THEN VacationHours + 40
ELSE (VacationHours + 20.00)
END
)
OUTPUT Deleted.BusinessEntityID, Deleted.VacationHours AS BeforeValue,
Inserted.VacationHours AS AfterValue
WHERE SalariedFlag = 0;
Using CASE
in a HAVING
clause
The following example uses the CASE
expression in a HAVING
clause to restrict the rows returned by the SELECT
statement. The statement returns the the maximum hourly rate for each job title in the HumanResources.Employee table. The HAVING
clause restricts the titles to those that are held by men with a maximum pay rate greater than 40 dollars or women with a maximum pay rate greater than 42 dollars.
USE AdventureWorks2012;
GO
SELECT JobTitle, MAX(ph1.Rate)AS MaximumRate
FROM HumanResources.Employee AS e
JOIN HumanResources.EmployeePayHistory AS ph1 ON e.BusinessEntityID = ph1.BusinessEntityID
GROUP BY JobTitle
HAVING (MAX(CASE WHEN Gender = 'M'
THEN ph1.Rate
ELSE NULL END) > 40.00
OR MAX(CASE WHEN Gender = 'F'
THEN ph1.Rate
ELSE NULL END) > 42.00)
ORDER BY MaximumRate DESC;
For more details description of these example visit the source.
Also visit here and here for some examples with great details.
In addition to the excellent answers above, let me offer you a link to the following article (by Patrick Thomson) which explains monads by relating the concept to the JavaScript library jQuery (and its way of using "method chaining" to manipulate the DOM): jQuery is a Monad
The jQuery documentation itself doesn't refer to the term "monad" but talks about the "builder pattern" which is probably more familiar. This doesn't change the fact that you have a proper monad there maybe without even realizing it.
Use re.search(r'\((.*?)\)',s).group(1)
:
>>> import re
>>> s = u'abcde(date=\'2/xc2/xb2\',time=\'/case/test.png\')'
>>> re.search(r'\((.*?)\)',s).group(1)
u"date='2/xc2/xb2',time='/case/test.png'"
@forelse ($users as $user)
<li>{{ $user->name }}</li>
@empty
<p>No users</p>
@endforelse
Thanks, Bendin. I like your solution very much.
I changed it to work in reverse order, showing most recent changes first. Which is important with long standing code, maintained over several years. I usually pipe it into more.
svnhistory elements.py |more
I added -r to the sort. I removed spec. handling for 'first record'. It is it will error out on the last entry, as there is nothing to diff it with. Though I am living with it because I never get down that far.
#!/bin/bash
# history_of_file
#
# Bendin on Stack Overflow: http://stackoverflow.com/questions/282802
# Outputs the full history of a given file as a sequence of
# logentry/diff pairs. The first revision of the file is emitted as
# full text since there's not previous version to compare it to.
#
# Dlink
# Made to work in reverse order
function history_of_file() {
url=$1 # current url of file
svn log -q $url | grep -E -e "^r[[:digit:]]+" -o | cut -c2- | sort -nr | {
while read r
do
echo
svn log -r$r $url@HEAD
svn diff -c$r $url@HEAD
echo
done
}
}
history_of_file $1
On macOS you can simply use -[NSString isCaseInsensitiveLike:]
, which returns BOOL
just like -isEqual:
.
if ([@"Test" isCaseInsensitiveLike: @"test"])
// Success
A change was introduced recently in how Facebook handles session redirects. See "Change in Session Redirect Behavior" in this week's Operation Developer Love blog post for the announcement.
z-index
only applies to elements that have been given an explicit position. Add position:relative
to #popupContent and you should be good to go.
Yep, Oracle has temporary tables. Here is a link to an AskTom article describing them and here is the official oracle CREATE TABLE documentation.
However, in Oracle, only the data in a temporary table is temporary. The table is a regular object visible to other sessions. It is a bad practice to frequently create and drop temporary tables in Oracle.
CREATE GLOBAL TEMPORARY TABLE today_sales(order_id NUMBER)
ON COMMIT PRESERVE ROWS;
Oracle 18c added private temporary tables, which are single-session in-memory objects. See the documentation for more details. Private temporary tables can be dynamically created and dropped.
CREATE PRIVATE TEMPORARY TABLE ora$ptt_today_sales AS
SELECT * FROM orders WHERE order_date = SYSDATE;
Temporary tables can be useful but they are commonly abused in Oracle. They can often be avoided by combining multiple steps into a single SQL statement using inline views.
You can pass your arguments using this encodeURIComponent function so you don't have to worry about passing any special characters.
data: "param1=getAccNos¶m2="+encodeURIComponent('Dolce & Gabbana')
OR
var someValue = 'Dolce & Gabbana';
data: "param1=getAccNos¶m2="+encodeURIComponent(someValue)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent
a = [0,1,2,3,127,200,255]
print str.join("", ("%02x" % i for i in a))
prints
000102037fc8ff
(Also note that your code will fail for integers in the range from 10 to 15.)
There are multiple options. See Split single comma delimited string into rows in Oracle
You just need to add LEVEL in the select list as a column, to get the sequence number to each row returned. Or, ROWNUM would also suffice.
Using any of the below SQLs, you could include them into a FUNCTION.
INSTR in CONNECT BY clause:
SQL> WITH DATA AS 2 ( SELECT 'word1, word2, word3, word4, word5, word6' str FROM dual 3 ) 4 SELECT trim(regexp_substr(str, '[^,]+', 1, LEVEL)) str 5 FROM DATA 6 CONNECT BY instr(str, ',', 1, LEVEL - 1) > 0 7 / STR ---------------------------------------- word1 word2 word3 word4 word5 word6 6 rows selected. SQL>
REGEXP_SUBSTR in CONNECT BY clause:
SQL> WITH DATA AS 2 ( SELECT 'word1, word2, word3, word4, word5, word6' str FROM dual 3 ) 4 SELECT trim(regexp_substr(str, '[^,]+', 1, LEVEL)) str 5 FROM DATA 6 CONNECT BY regexp_substr(str , '[^,]+', 1, LEVEL) IS NOT NULL 7 / STR ---------------------------------------- word1 word2 word3 word4 word5 word6 6 rows selected. SQL>
REGEXP_COUNT in CONNECT BY clause:
SQL> WITH DATA AS 2 ( SELECT 'word1, word2, word3, word4, word5, word6' str FROM dual 3 ) 4 SELECT trim(regexp_substr(str, '[^,]+', 1, LEVEL)) str 5 FROM DATA 6 CONNECT BY LEVEL
Using XMLTABLE
SQL> WITH DATA AS 2 ( SELECT 'word1, word2, word3, word4, word5, word6' str FROM dual 3 ) 4 SELECT trim(COLUMN_VALUE) str 5 FROM DATA, xmltable(('"' || REPLACE(str, ',', '","') || '"')) 6 / STR ------------------------------------------------------------------------ word1 word2 word3 word4 word5 word6 6 rows selected. SQL>
Using MODEL clause:
SQL> WITH t AS 2 ( 3 SELECT 'word1, word2, word3, word4, word5, word6' str 4 FROM dual ) , 5 model_param AS 6 ( 7 SELECT str AS orig_str , 8 ',' 9 || str 10 || ',' AS mod_str , 11 1 AS start_pos , 12 Length(str) AS end_pos , 13 (Length(str) - Length(Replace(str, ','))) + 1 AS element_count , 14 0 AS element_no , 15 ROWNUM AS rn 16 FROM t ) 17 SELECT trim(Substr(mod_str, start_pos, end_pos-start_pos)) str 18 FROM ( 19 SELECT * 20 FROM model_param MODEL PARTITION BY (rn, orig_str, mod_str) 21 DIMENSION BY (element_no) 22 MEASURES (start_pos, end_pos, element_count) 23 RULES ITERATE (2000) 24 UNTIL (ITERATION_NUMBER+1 = element_count[0]) 25 ( start_pos[ITERATION_NUMBER+1] = instr(cv(mod_str), ',', 1, cv(element_no)) + 1, 26 end_pos[iteration_number+1] = instr(cv(mod_str), ',', 1, cv(element_no) + 1) ) ) 27 WHERE element_no != 0 28 ORDER BY mod_str , 29 element_no 30 / STR ------------------------------------------ word1 word2 word3 word4 word5 word6 6 rows selected. SQL>
You could also use DBMS_UTILITY package provided by Oracle. It provides various utility subprograms. One such useful utility is COMMA_TO_TABLE procedure, which converts a comma-delimited list of names into a PL/SQL table of names.
It's recommended to put the image to the resources, than you can use it like this:
imageView = new ImageView("/gui.img/img.jpg");
The guide linked here will probably answer the original question without the need for programming a custom SSL connector.
Found a very detailed how-to guide on importing root certificates that actually steps you through installing trusted CA certificates on different versions of Android devices (among other devices).
Basically you'll need to:
Download: the cacerts.bks file from your phone.
adb pull /system/etc/security/cacerts.bks cacerts.bks
Download the .crt file from the certifying authority you want to allow.
Modify the cacerts.bks file on your computer using the BouncyCastle Provider
Upload the cacerts.bks file back to your phone and reboot.
Here is a more detailed step by step to update earlier android phones: How to update HTTPS security certificate authority keystore on pre-android-4.0 device
I got this error when one of my properties that was required for the constructor was not public. Make sure all the parameters in the constructor go to properties that are public if this is the case:
using statements namespace someNamespace
public class ExampleClass {
//Properties - one is not visible to the class calling the constructor
public string Property1 { get; set; }
string Property2 { get; set; }
//Constructor
public ExampleClass(string property1, string property2)
{
this.Property1 = property1;
this.Property2 = property2; //this caused that error for me
}
}
If you don't want to be IDE dependent and want to work directly with the command line, you can use 'jdb' (Java Debugger)
As mentioned by Samuel with small modification (set suspend=y instead of suspend=n, y means yes which suspends the program and not run it so you that can set breakpoints to debug it, if suspend=n means it may run the program to completion before you can even debug it)
On the directory which contains your pom.xml, execute:
mvn exec:exec -Dexec.executable="java" -Dexec.args="-classpath %classpath -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=1044 com.mycompany.app.App"
Then, open up a new terminal and execute:
jdb -attach 1044
You can then use jdb to debug your program!=)
An alternative to Tushar Gupta answer would be :
'14 2'.split(' ').map(x=>+x);
// [14, 2]`
In code golf you save 1 character. Here the "+" is "unary plus" operator, works like parseInt.
I found that when you use the action buttons in expanded notifications, you have to write extra code and you are more constrained.
You have to manually cancel your notification when the user clicks an action button. The notification is only cancelled automatically for the default action.
Also if you start a broadcast receiver from the button, the notification drawer doesn't close.
I ended up creating a new NotificationActivity to address these issues. This intermediary activity without any UI cancels the notification and then starts the activity I really wanted to start from the notification.
I've posted sample code in a related post Clicking Android Notification Actions does not close Notification drawer.
There are two ways for writing a proper media queries in css. If you are writing media queries for larger device first, then the correct way of writing will be:
@media only screen
and (min-width : 415px){
/* Styles */
}
@media only screen
and (min-width : 769px){
/* Styles */
}
@media only screen
and (min-width : 992px){
/* Styles */
}
But if you are writing media queries for smaller device first, then it would be something like:
@media only screen
and (max-width : 991px){
/* Styles */
}
@media only screen
and (max-width : 768px){
/* Styles */
}
@media only screen
and (max-width : 414px){
/* Styles */
}
I found the same issue when upgrading to pgAdmin 4 (v1.6). On Windows I found that clearing out the C:\Users\%USERNAME%\AppData\Roaming\pgAdmin
folder fixed the issue for me. I believe it was attempting to use the sessions from the prior version and was failing. I know the question was marked as answered, but downgrading may not always be an option.
Note: AppData\Roaming\pgAdmin is a hidden folder.
Drawable d = getResources().getDrawable(android.R.drawable.ic_dialog_email);
ImageView image = (ImageView)findViewById(R.id.image);
image.setImageDrawable(d);
This is the problem
double a[] = null;
Since a
is null
, NullPointerException
will arise every time you use it until you initialize it. So this:
a[i] = var;
will fail.
A possible solution would be initialize it when declaring it:
double a[] = new double[PUT_A_LENGTH_HERE]; //seems like this constant should be 7
IMO more important than solving this exception, is the fact that you should learn to read the stacktrace and understand what it says, so you could detect the problems and solve it.
java.lang.NullPointerException
This exception means there's a variable with null
value being used. How to solve? Just make sure the variable is not null
before being used.
at twoten.TwoTenB.(TwoTenB.java:29)
This line has two parts:
<init>
method in class TwoTenB
declared in package twoten
. When you encounter an error message with SomeClassName.<init>
, means the error was thrown while creating a new instance of the class e.g. executing the constructor (in this case that seems to be the problem).a[i] = var;
.From this line, other lines will be similar to tell you where the error arose. So when reading this:
at javapractice.JavaPractice.main(JavaPractice.java:32)
It means that you were trying to instantiate a TwoTenB
object reference inside the main
method of your class JavaPractice
declared in javapractice
package.
If you are fine with modifying the original set (which you may want to do in some cases), you can use set.update()
:
S.update(T)
The return value is None
, but S
will be updated to be the union of the original S
and T
.
C:\Program Files\NetBeans 8.2\etc\netbeans.conf
netbeans_jdkhome="C:\Program Files\Java\jdk1.8.0_171"
Does it have to be a string[] ? A List<String> would give you what you need.
List<String> testing = new List<String>();
testing.Add("One");
testing.Add("Two");
testing.Add("Three");
testing.Add("Mouse");
bool inList = testing.Contains("Mouse");
I haven't fully explored the TPL but they might have something that fits your needs, or at the very least, some Reflector fodder to snag some inspiration from.
Hope that helps.
On Linux we can have these as exceptions, too.
Normally, when your program performs a segmentation fault, it is sent a SIGSEGV
signal. You can set up your own handler for this signal and mitigate the consequences. Of course you should really be sure that you can recover from the situation. In your case, I think, you should debug your code instead.
Back to the topic. I recently encountered a library (short manual) that transforms such signals to exceptions, so you can write code like this:
try
{
*(int*) 0 = 0;
}
catch (std::exception& e)
{
std::cerr << "Exception caught : " << e.what() << std::endl;
}
Didn't check it, though. Works on my x86-64 Gentoo box. It has a platform-specific backend (borrowed from gcc's java implementation), so it can work on many platforms. It just supports x86 and x86-64 out of the box, but you can get backends from libjava, which resides in gcc sources.
context path can be directly integrated to the code but it is not advisable since it cannot be reused so write in the application.properties file server.contextPath=/name of the folder where you placed the code contextPath = name of the folder where you placed the code/ Note:watch the slash carefully.
Linux does not have any system variables that give the current CPU utilization. Instead, you have to read /proc/stat
several times: each column in the cpu(n)
lines gives the total CPU time, and you have to take subsequent readings of it to get percentages. See this document to find out what the various columns mean.
Try it. You can get Device Name through Bluetooth.
Hope it will help you
public String getPhoneName() {
BluetoothAdapter myDevice = BluetoothAdapter.getDefaultAdapter();
String deviceName = myDevice.getName();
return deviceName;
}
If you are not looking for Excel formula, Its easy from the Menu
Data Menu --> Remove Duplicates would alert, if there are no duplicates
Also, if you see the count and reduced after removing duplicates...
Edit (2020.12.28): GitHub change default master branch to main branch since October 2020. See https://github.com/github/renaming
Update March 2013
Git 1.8.2 added the possibility to track branches.
"
git submodule
" started learning a new mode to integrate with the tip of the remote branch (as opposed to integrating with the commit recorded in the superproject's gitlink).
# add submodule to track master branch
git submodule add -b master [URL to Git repo];
# update your submodule
git submodule update --remote
If you had a submodule already present you now wish would track a branch, see "how to make an existing submodule track a branch".
Also see Vogella's tutorial on submodules for general information on submodules.
Note:
git submodule add -b . [URL to Git repo];
^^^
A special value of
.
is used to indicate that the name of the branch in the submodule should be the same name as the current branch in the current repository.
See commit b928922727d6691a3bdc28160f93f25712c565f6:
submodule add
: If --branch
is given, record it in .gitmodules
This allows you to easily record a
submodule.<name>.branch
option in.gitmodules
when you add a new submodule. With this patch,
$ git submodule add -b <branch> <repository> [<path>]
$ git config -f .gitmodules submodule.<path>.branch <branch>
reduces to
$ git submodule add -b <branch> <repository> [<path>]
This means that future calls to
$ git submodule update --remote ...
will get updates from the same branch that you used to initialize the submodule, which is usually what you want.
Signed-off-by: W. Trevor King [email protected]
Original answer (February 2012):
A submodule is a single commit referenced by a parent repo.
Since it is a Git repo on its own, the "history of all commits" is accessible through a git log
within that submodule.
So for a parent to track automatically the latest commit of a given branch of a submodule, it would need to:
gitslave (that you already looked at) seems to be the best fit, including for the commit operation.
It is a little annoying to make changes to the submodule due to the requirement to check out onto the correct submodule branch, make the change, commit, and then go into the superproject and commit the commit (or at least record the new location of the submodule).
Other alternatives are detailed here.
You can use the grep alternative sift here (disclaimer: I am the author).
It support multiline matching and limiting the search to specific file types out of the box:
sift -m --files '*.py' 'YOUR_PATTERN'
(search all *.py files for the specified multiline regex pattern)
It is available for all major operating systems. Take a look at the samples page to see how it can be used to to extract multiline values from an XML file.
one-liner with streams
Stream.concat(Arrays.stream( array ), Stream.of( newElement )).toArray();
For
@Url.Action
<a href="@Url.Action("Action", "Controller")" target="_blank">Link Text</a>
Just change
import android.widget.Toolbar;
To
import android.support.v7.widget.Toolbar;
This is a safety measure to avoid pushing branches that are not ready to be published. Loosely speaking, by executing "git push", only local branches that already exist on the server with the same name will be pushed, or branches that have been pushed using the localbranch:remotebranch syntax.
To push all local branches to the remote repository, use --all
:
git push REMOTENAME --all
git push --all
or specify all branches you want to push:
git push REMOTENAME master exp-branch-a anotherbranch bugfix
In addition, it's useful to add -u
to the "git push" command, as this will tell you if your local branch is ahead or behind the remote branch. This is shown when you run "git status" after a git fetch.
If you need to hit the database, you need to hit the web server again (for the most part).
What you can do is use AJAX, which makes a request to another script on your site to retrieve data, gets the data, and then updates the input fields you want.
AJAX calls can be made in jquery with the $.ajax() function call, so this will happen
User's browser enters input that fires a trigger that makes an AJAX call
$('input .callAjax').bind('change', function() {
$.ajax({ url: 'script/ajax',
type: json
data: $foo,
success: function(data) {
$('input .targetAjax').val(data.newValue);
});
);
Now you will need to point that AJAX call at script (sounds like you're working PHP) that will do the query you want and send back data.
You will probably want to use the JSON object call so you can pass back a javascript object, that will be easier to use than return XML etc.
The php function json_encode($phpobj); will be useful.
Use a Bundle
. Here's an example:
Fragment fragment = new Fragment();
Bundle bundle = new Bundle();
bundle.putInt(key, value);
fragment.setArguments(bundle);
Bundle has put methods for lots of data types. See this
Then in your Fragment
, retrieve the data (e.g. in onCreate()
method) with:
Bundle bundle = this.getArguments();
if (bundle != null) {
int myInt = bundle.getInt(key, defaultValue);
}
Had forgotten this issue... I was actually asking with Eclipse, sorry for not stating that originally. And the answer seems to be too simple (at least with 3.5; probably with older versions also):
Java run configuration's Arguments : VM arguments:
-Djava.library.path="${workspace_loc:project}\lib;${env_var:PATH}"
Must not forget the quotation marks, otherwise there are problems with spaces in PATH.
You can create the ipa for ad hoc distribution and use diawi to create a link for the your ipad. You just upload the .ipa and the provisioning profile, then a link is generated and you can visit it from your ipad in order to install the app (if the provisioning profile is for development you have to add your ipad's UDID to it).
I had a similar problem. The incorrect credentials were cached in OS X's key-chain.
Check out: https://help.github.com/articles/updating-credentials-from-the-osx-keychain
def find_pos(chaine,x):
for i in range(len(chaine)):
if chaine[i] ==x :
return 'yes',i
return 'no'
Hi this worked for me "/opt/lampp/xampp security" in Centos
[root@XXXXX ~]# /opt/lampp/xampp security
XAMPP: Quick security check...
XAMPP: Your XAMPP pages are secured by a password.
XAMPP: Do you want to change the password anyway? [no] yes
XAMPP: Password:
XAMPP: Password (again):
XAMPP: Password protection active. Please use 'xampp' as user name!
XAMPP: MySQL is not accessable via network. Good.
XAMPP: MySQL has a root passwort set. Fine! :)
XAMPP: The FTP password for user 'daemon' is still set to 'xampp'.
XAMPP: Do you want to change the password? [yes]
XAMPP: Password:
XAMPP: Password (again):
XAMPP: Reload ProFTPD...ok.
XAMPP: Done.
[root@XXXXX ~]#
I found that when the widget is part of a function and the grid_remove
is part of another function it does not remove the label. In this example...
def somefunction(self):
Label(self, text=" ").grid(row = 0, column = 0)
self.text_ent = Entry(self)
self.text_ent.grid(row = 1, column = 0)
def someotherfunction(self):
somefunction.text_ent.grid_remove()
...there is no valid way of removing the Label.
The only solution I could find is to give the label a name and make it global:
def somefunction(self):
global label
label = Label(self, text=" ")
label.grid(row = 0, column = 0)
self.text_ent = Entry(self)
self.text_ent.grid(row = 1, column = 0)
def someotherfunction(self):
global label
somefunction.text_ent.grid_remove()
label.grid_remove()
When I ran into this problem there was a class involved, one function being in the class and one not, so I'm not sure the global label
lines are really needed in the above.
If you're using WPF and the previous answers don't help, you can retrieve the result using:
var result = MessageBox.Show("Message", "caption", MessageBoxButton.YesNo, MessageBoxImage.Question);
if (result == MessageBoxResult.Yes)
{
// Do something
}
Add following at start of cell and run it:
from IPython.display import clear_output
clear_output(wait=True)
This example produces a nested repeater where the outer data includes an inner array which I wanted to list in two column. The concept would hold true for three or more columns.
In the inner column I repeat the "row" until the limit is reached. The limit is determined by dividing the length of the array of items by the number of columns desired, in this case by two. The division method sits on the controller and is passed the current array length as a parameter. The JavaScript slice(0, array.length / columnCount) function then applied the limit to the repeater.
The second column repeater is then invoked and repeats slice( array.length / columnCount, array.length) which produces the second half of the array in column two.
<div class="row" ng-repeat="GroupAccess in UsersController.SelectedUser.Access" ng-class="{even: $even, odd: $odd}">
<div class="col-md-12 col-xs-12" style=" padding-left:15px;">
<label style="margin-bottom:2px;"><input type="checkbox" ng-model="GroupAccess.isset" />{{GroupAccess.groupname}}</label>
</div>
<div class="row" style=" padding-left:15px;">
<div class="col-md-1 col-xs-0"></div>
<div class="col-md-3 col-xs-2">
<div style="line-height:11px; margin-left:2px; margin-bottom:2px;" ng-repeat="Feature in GroupAccess.features.slice(0, state.DivideBy2(GroupAccess.features.length))">
<span class="GrpFeature">{{Feature.featurename}}</span>
</div>
</div>
<div class="col-md-3 col-xs-2">
<div style="line-height:11px; margin-left:2px; margin-bottom:2px;" ng-repeat="Feature in GroupAccess.features.slice( state.DivideBy2(GroupAccess.features.length), GroupAccess.features.length )">
<span class="GrpFeature">{{Feature.featurename}}</span>
</div>
</div>
<div class="col-md-5 col-xs-8">
</div>
</div>
</div>
// called to format two columns
state.DivideBy2 = function(nValue) {
return Math.ceil(nValue /2);
};
Hope this helps to look at the solution in yet another way. (PS this is my first post here! :-))
As help to anybody that had the same problem as me, I accidentally mistyped the implementation type instead of the interface e.g.
var mockFileBrowser = new Mock<FileBrowser>();
instead of
var mockFileBrowser = new Mock<IFileBrowser>();
Go to Gradle tab in Android Studio , then select library project .
Then go to Tasks
Then go to Other
Double click on bundleReleaseaar
You can find your .aar
files under your_module/build/outputs/aar/your-release.aar
The reason your tests are all being run is that you have the --filter
flag after the file name. PHPUnit is not reading the options at all and so is running all the test cases.
From the help screen:
Usage: phpunit [options] UnitTest [UnitTest.php]
phpunit [options] <directory>
So move the --filter
argument before the test file that you want as mentioned in @Alex and
@Ferid Mövsümov answers. And you should only have the test that you want run.
Add this statement into AppDelegate.h
//whether to allow cross screen marker
@property (nonatomic, assign) allowRotation BOOL;
Write down this section of code into AppDelegate.m
- (UIInterfaceOrientationMask) application: (UIApplication *) supportedInterfaceOrientationsForWindow: application (UIWindow *) window {
If (self.allowRotation) {
UIInterfaceOrientationMaskAll return;
}
UIInterfaceOrientationMaskPortrait return;
}
Change the allowRotation
property of delegate app
PostgreSQL Create Database - Steps to create database in Postgres.
su - postgres
bash-4.1$ psql psql (12.1) Type "help" for help. postgres=#
CREATE DATABASE database_name;
Check for detailed information below: https://orahow.com/postgresql-create-database/
Either return text/plain
(as in Return only string message from Spring MVC 3 Controller) OR wrap your String is some object
public class StringResponse {
private String response;
public StringResponse(String s) {
this.response = s;
}
// get/set omitted...
}
Set your response type to MediaType.APPLICATION_JSON_VALUE
(= "application/json"
)
@RequestMapping(value = "/getString", method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
and you'll have a JSON that looks like
{ "response" : "your string value" }
In my case I had Java 7 and 8 (both x64) installed and I want to redirect to java 7 but everything is set to use Java 8. Java uses the PATH environment variable:
C:\ProgramData\Oracle\Java\javapath
as the first option to look for its folder runtime (is a hidden folder). This path contains 3 symlinks that can't be edited.
In my pc, the PATH environment variable looks like this:
C:\ProgramData\Oracle\Java\javapath;C:\Windows\System32;C:\Program Files\Java\jdk1.7.0_21\bin;
In my case, It should look like this:
C:\Windows\System32;C:\Program Files\Java\jdk1.7.0_21\bin;
I had to cut and paste the symlinks to somewhere else so java can't find them, and I can restore them later.
After setting the JAVA_HOME and JRE_HOME environment variables to the desired java folders' runtimes (in my case it is Java 7), the command java -version
should show your desired java runtime. I remark there's no need to mess with the registry.
Tested on Win7 x64.
To facilitate potentially solving your problem given the information you've provided, I'm going to assume you're seeking dynamic CSS. If this is the case, you can use a server-side scripting language to do so. For example (and I absolutely love doing things like this):
styles.css.php:
body
{
margin: 0px;
font-family: Verdana;
background-color: #cccccc;
background-image: url('<?php
echo 'images/flag_bg/' . $user_country . '.png';
?>');
}
This would set the background image to whatever was stored in the $user_country variable. This is only one example of dynamic CSS; there are virtually limitless possibilities when combining CSS and server-side code. Another case would be doing something like allowing the user to create a custom theme, storing it in a database, and then using PHP to set various properties, like so:
user_theme.css.php:
body
{
background-color: <?php echo $user_theme['BG_COLOR']; ?>;
color: <?php echo $user_theme['COLOR']; ?>;
font-family: <?php echo $user_theme['FONT']; ?>;
}
#panel
{
font-size: <?php echo $user_theme['FONT_SIZE']; ?>;
background-image: <?php echo $user_theme['PANEL_BG']; ?>;
}
Once again, though, this is merely an off-the-top-of-the-head example; harnessing the power of dynamic CSS via server-side scripting can lead to some pretty incredible stuff.
To String
import strings
stringFiles := strings.Join(fileSlice[:], ",")
Back to Slice again
import strings
fileSlice := strings.Split(stringFiles, ",")
You can pass as many arguments as you want, separating them by commas:
{{ path('_files_manage', {project: project.id, user: user.id}) }}
Or you can use simply preload="none"
attribute to make VIDEO background visible. And you can use background-size: cover;
here.
video {
background: transparent url('video-image.jpg') 50% 50% / cover no-repeat ;
}
<video preload="none" controls>
<source src="movie.mp4" type="video/mp4">
<source src="movie.ogg" type="video/ogg">
</video>
Change key in Project > Build Setting "typecheck calls to printf/scanf : NO"
Explanation : [How it works]
Check calls to printf and scanf, etc., to make sure that the arguments supplied have types appropriate to the format string specified, and that the conversions specified in the format string make sense.
Hope it work
Other warning
objective c implicit conversion loses integer precision 'NSUInteger' (aka 'unsigned long') to 'int
Change key "implicit conversion to 32Bits Type > Debug > *64 architecture : No"
[caution: It may void other warning of 64 Bits architecture conversion].
There is a Hidden
helper alongside HiddenFor
which lets you set the value.
@Html.Hidden("RequiredProperty", "default")
EDIT Based on the edit you've made to the question, you could do this, but I believe you're moving into territory where it will be cheaper and more effective, in the long run, to fight for making the code change. As has been said, even by yourself, the controller or view model should be setting the default.
This code:
<ul>
@{
var stacks = new System.Diagnostics.StackTrace().GetFrames();
foreach (var frame in stacks)
{
<li>@frame.GetMethod().Name - @frame.GetMethod().DeclaringType</li>
}
}
</ul>
Will give output like this:
Execute - ASP._Page_Views_ViewDirectoryX__SubView_cshtml
ExecutePageHierarchy - System.Web.WebPages.WebPageBase
ExecutePageHierarchy - System.Web.Mvc.WebViewPage
ExecutePageHierarchy - System.Web.WebPages.WebPageBase
RenderView - System.Web.Mvc.RazorView
Render - System.Web.Mvc.BuildManagerCompiledView
RenderPartialInternal - System.Web.Mvc.HtmlHelper
RenderPartial - System.Web.Mvc.Html.RenderPartialExtensions
Execute - ASP._Page_Views_ViewDirectoryY__MainView_cshtml
So assuming the MVC framework will always go through the same stack, you can grab var frame = stacks[8];
and use the declaring type to determine who your parent view is, and then use that determination to set (or not) the default value. You could also walk the stack instead of directly grabbing [8]
which would be safer but even less efficient.
The old-school ugly method. Use the ExitWindowsEx
function from the Win32 API.
using System.Runtime.InteropServices;
void Shutdown2()
{
const string SE_SHUTDOWN_NAME = "SeShutdownPrivilege";
const short SE_PRIVILEGE_ENABLED = 2;
const uint EWX_SHUTDOWN = 1;
const short TOKEN_ADJUST_PRIVILEGES = 32;
const short TOKEN_QUERY = 8;
IntPtr hToken;
TOKEN_PRIVILEGES tkp;
// Get shutdown privileges...
OpenProcessToken(Process.GetCurrentProcess().Handle,
TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, out hToken);
tkp.PrivilegeCount = 1;
tkp.Privileges.Attributes = SE_PRIVILEGE_ENABLED;
LookupPrivilegeValue("", SE_SHUTDOWN_NAME, out tkp.Privileges.pLuid);
AdjustTokenPrivileges(hToken, false, ref tkp, 0U, IntPtr.Zero,
IntPtr.Zero);
// Now we have the privileges, shutdown Windows
ExitWindowsEx(EWX_SHUTDOWN, 0);
}
// Structures needed for the API calls
private struct LUID
{
public int LowPart;
public int HighPart;
}
private struct LUID_AND_ATTRIBUTES
{
public LUID pLuid;
public int Attributes;
}
private struct TOKEN_PRIVILEGES
{
public int PrivilegeCount;
public LUID_AND_ATTRIBUTES Privileges;
}
[DllImport("advapi32.dll")]
static extern int OpenProcessToken(IntPtr ProcessHandle,
int DesiredAccess, out IntPtr TokenHandle);
[DllImport("advapi32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool AdjustTokenPrivileges(IntPtr TokenHandle,
[MarshalAs(UnmanagedType.Bool)]bool DisableAllPrivileges,
ref TOKEN_PRIVILEGES NewState,
UInt32 BufferLength,
IntPtr PreviousState,
IntPtr ReturnLength);
[DllImport("advapi32.dll")]
static extern int LookupPrivilegeValue(string lpSystemName,
string lpName, out LUID lpLuid);
[DllImport("user32.dll", SetLastError = true)]
static extern int ExitWindowsEx(uint uFlags, uint dwReason);
In production code you should be checking the return values of the API calls, but I left that out to make the example clearer.
I realized it was a port issue since I was running IIS and other web servers in my machine. But I was more interested to see a detailed error message with the port number in the UI.
Seems like it was not logged in the UI or log file (at least in my case), but in the Event viewer (Control panel -> View Event Logs). Under the Even viewer -> Windows Logs -> Application
I could see a permission error something like the below one:
An attempt was made to access a socket in a way forbidden by its access permissions. : AH00072: make_sock: could not bind to address 0.0.0.0:443
To fix this permission issue for SSL port, Please change the below line in httpd-ssl.conf (C:\xampp\apache\conf\extra)
# When we also provide SSL we have to listen to the
standard HTTP port (see above) and to the HTTPS port
Listen xxx
Replace XXX with any valid port number that is open in your machine
If you are having issues with Port 80, then change the httpd.conf file (C:\xampp\apache\conf)
# Change this to Listen on specific IP addresses as shown below to
# prevent Apache from glomming onto all bound IP addresses.
#
#Listen 12.34.56.78:80
Listen 127.0.0.1:8000
I have also summarized other solutions that I came across:
[SOLVED]
I only observed this error today, for me the Error code was different though.
SCRIPT7002: XMLHttpRequest: Network Error 0x2efd, Could not complete the operation due to error 00002efd.
It was occurring randomly and not all the time. but what it noticed is, if it comes for subsequent ajax calls. so i put some delay of 5 seconds between the ajax calls and it resolved.
I think your question is similar to this thread: JDBC Pagination which contains solutions for your need.
In particular, for PostgreSQL, you can use the LIMIT and OFFSET keywords in your request: http://www.petefreitag.com/item/451.cfm
PS: In Java code, I suggest you to use PreparedStatement instead of simple Statements: http://download.oracle.com/javase/tutorial/jdbc/basics/prepared.html
Possible solution that worked for me with jest
import React from "react";
import { shallow } from "enzyme";
import { Provider } from "react-redux";
import configureMockStore from "redux-mock-store";
import TestPage from "../TestPage";
const mockStore = configureMockStore();
const store = mockStore({});
describe("Testpage Component", () => {
it("should render without throwing an error", () => {
expect(
shallow(
<Provider store={store}>
<TestPage />
</Provider>
).exists(<h1>Test page</h1>)
).toBe(true);
});
});
There are two different types of quotation marks in MySQL. You need to use ` for column names and ' for strings. Since you have used ' for the filename column the query parser got confused. Either remove the quotation marks around all column names, or change 'filename' to `filename`. Then it should work.
The fastest way is this:
$.getJSON("/Admin/GetFolderList/", function(result) {
var optionsValues = '<select>';
$.each(result, function(item) {
optionsValues += '<option value="' + item.ImageFolderID + '">' + item.Name + '</option>';
});
optionsValues += '</select>';
var options = $('#options');
options.replaceWith(optionsValues);
});
According to this link is the fastest way because you wrap everything in a single element when doing any kind of DOM insertion.
Define a new handler and runnable:
private Handler handler = new Handler(Looper.getMainLooper());
private Runnable runnable = new Runnable() {
@Override
public void run() {
// Do what ever you want
}
};
Call post delayed:
handler.postDelayed(runnable, sleep_time);
Remove your callback from your handler:
handler.removeCallbacks(runnable);
If you are on either Eclipse or Spring tool suite then follow the below steps.
(1) Go to 'Window' on the top of the editor. Click on it
(2) Select show view. You should see an option 'Project Explorer'. Click on it.
You should be able to do it.
There is a known problem with Java and glibc >= 2.10 (includes Ubuntu >= 10.04, RHEL >= 6).
The cure is to set this env. variable:
export MALLOC_ARENA_MAX=4
If you are running Tomcat, you can add this to TOMCAT_HOME/bin/setenv.sh
file.
For Docker, add this to Dockerfile
ENV MALLOC_ARENA_MAX=4
There is an IBM article about setting MALLOC_ARENA_MAX https://www.ibm.com/developerworks/community/blogs/kevgrig/entry/linux_glibc_2_10_rhel_6_malloc_may_show_excessive_virtual_memory_usage?lang=en
resident memory has been known to creep in a manner similar to a memory leak or memory fragmentation.
There is also an open JDK bug JDK-8193521 "glibc wastes memory with default configuration"
search for MALLOC_ARENA_MAX on Google or SO for more references.
You might want to tune also other malloc options to optimize for low fragmentation of allocated memory:
# tune glibc memory allocation, optimize for low fragmentation
# limit the number of arenas
export MALLOC_ARENA_MAX=2
# disable dynamic mmap threshold, see M_MMAP_THRESHOLD in "man mallopt"
export MALLOC_MMAP_THRESHOLD_=131072
export MALLOC_TRIM_THRESHOLD_=131072
export MALLOC_TOP_PAD_=131072
export MALLOC_MMAP_MAX_=65536
The elements of a sequence need to be indented at the same level. Assuming you want two jobs (A and B) each with an ordered list of key value pairs, you should use:
jobs:
- - name: A
- schedule: "0 0/5 * 1/1 * ? *"
- - type: mongodb.cluster
- config:
- host: mongodb://localhost:27017/admin?replicaSet=rs
- minSecondaries: 2
- minOplogHours: 100
- maxSecondaryDelay: 120
- - name: B
- schedule: "0 0/5 * 1/1 * ? *"
- - type: mongodb.cluster
- config:
- host: mongodb://localhost:27017/admin?replicaSet=rs
- minSecondaries: 2
- minOplogHours: 100
- maxSecondaryDelay: 120
Converting the sequences of (single entry) mappings to a mapping as @Tsyvarrev does is also possible, but makes you lose the ordering.
Just add use of origin in your if you use node.js as server...
like this
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
next();
});
We Need response for origin
This problem occurred to me when using nested try- catch and using the $ex->getPrevious() function for logging exception .mabye your code has endless loop. So you first need to check the code and increase the size of the memory if necessary
try {
//get latest product data and latest stock from api
$latestStocksInfo = Product::getLatestProductWithStockFromApi();
} catch (\Exception $error) {
try {
$latestStocksInfo = Product::getLatestProductWithStockFromDb();
} catch (\Exception $ex) {
/*log exception */
Log::channel('report')->error(['message'=>$ex->getMessage(),'file'=>$ex->getFile(),'line'=>$ex->getLine(),'Previous'=>$ex->getPrevious()]);///------------->>>>>>>> this problem when use
Log::channel('report')->error(['message'=>$ex->getMessage(),'file'=>$ex->getFile(),'line'=>$ex->getLine()]);///------------->>>>>>>> this code is ok
}
Log::channel('report')->error(['message'=>$error->getMessage(),'file'=>$error->getFile(),'line'=>$error->getLine()]);
/***log exception ***/
}
There are four options here:
Get virtualenv
set up. Each virtual environment you create will automatically have pip
.
Learn how to install Python packages manually—in most cases it's as simple as download, unzip, python setup.py install
, but not always.
While it's possible to do a proper modulo by checking whether the value is negative and correct it if it is (the way many have suggested), there is a more compact solution.
(a % b + b) % b
This will first do the modulo, limiting the value to the -b -> +b range and then add b in order to ensure that the value is positive, letting the next modulo limit it to the 0 -> b range.
Note: If b is negative, the result will also be negative
Don't use CREATE TYPE to return a polymorphic result. Use and abuse the RECORD type instead. Check it out:
CREATE FUNCTION test_ret(a TEXT, b TEXT) RETURNS RECORD AS $$
DECLARE
ret RECORD;
BEGIN
-- Arbitrary expression to change the first parameter
IF LENGTH(a) < LENGTH(b) THEN
SELECT TRUE, a || b, 'a shorter than b' INTO ret;
ELSE
SELECT FALSE, b || a INTO ret;
END IF;
RETURN ret;
END;$$ LANGUAGE plpgsql;
Pay attention to the fact that it can optionally return two or three columns depending on the input.
test=> SELECT test_ret('foo','barbaz');
test_ret
----------------------------------
(t,foobarbaz,"a shorter than b")
(1 row)
test=> SELECT test_ret('barbaz','foo');
test_ret
----------------------------------
(f,foobarbaz)
(1 row)
This does wreak havoc on code, so do use a consistent number of columns, but it's ridiculously handy for returning optional error messages with the first parameter returning the success of the operation. Rewritten using a consistent number of columns:
CREATE FUNCTION test_ret(a TEXT, b TEXT) RETURNS RECORD AS $$
DECLARE
ret RECORD;
BEGIN
-- Note the CASTING being done for the 2nd and 3rd elements of the RECORD
IF LENGTH(a) < LENGTH(b) THEN
ret := (TRUE, (a || b)::TEXT, 'a shorter than b'::TEXT);
ELSE
ret := (FALSE, (b || a)::TEXT, NULL::TEXT);
END IF;
RETURN ret;
END;$$ LANGUAGE plpgsql;
Almost to epic hotness:
test=> SELECT test_ret('foobar','bar');
test_ret
----------------
(f,barfoobar,)
(1 row)
test=> SELECT test_ret('foo','barbaz');
test_ret
----------------------------------
(t,foobarbaz,"a shorter than b")
(1 row)
But how do you split that out in to multiple rows so that your ORM layer of choice can convert the values in to your language of choice's native data types? The hotness:
test=> SELECT a, b, c FROM test_ret('foo','barbaz') AS (a BOOL, b TEXT, c TEXT);
a | b | c
---+-----------+------------------
t | foobarbaz | a shorter than b
(1 row)
test=> SELECT a, b, c FROM test_ret('foobar','bar') AS (a BOOL, b TEXT, c TEXT);
a | b | c
---+-----------+---
f | barfoobar |
(1 row)
This is one of the coolest and most underused features in PostgreSQL. Please spread the word.
You can use button classes btn-link
and btn-xs
with type submit
, which will make a small invisible button with an icon inside of it. Example:
<button class="btn btn-link btn-xs" type="submit" name="action" value="delete">
<i class="fa fa-times text-danger"></i>
</button>
As your query string is a literal, and assuming your dates are properly stored as DATE
you should use date literals:
SELECT * FROM OrderArchive
WHERE OrderDate <= DATE '2015-12-31'
If you want to use TO_DATE
(because, for example, your query value is not a literal), I suggest you to explicitly set the NLS_DATE_LANGUAGE parameter as you are using US abbreviated month names. That way, it won't break on some localized Oracle Installation:
SELECT * FROM OrderArchive
WHERE OrderDate <= to_date('31 Dec 2014', 'DD MON YYYY',
'NLS_DATE_LANGUAGE = American');
Just adding a little more info.
JPA manages the version under the hood for you, however it doesn't do so when you update your record via JPAUpdateClause
, in such cases you need to manually add the version increment to the query.
Same can be said about updating via JPQL, i.e. not a simple change to the entity, but an update command to the database even if that is done by hibernate
Pedro
declare @ids table(idx int identity(1,1), id int)
insert into @ids (id)
select 4 union
select 7 union
select 12 union
select 22 union
select 19
declare @i int
declare @cnt int
select @i = min(idx) - 1, @cnt = max(idx) from @ids
while @i < @cnt
begin
select @i = @i + 1
declare @id = select id from @ids where idx = @i
exec p_MyInnerProcedure @id
end
I've created a class which helps to reduce errors in setting up custom handlers and takes advantage of the system property so there are no issues with calling a method first or not being in the right container. There's also an exception class if you get things wrong:
CustomURLScheme.java:
/*
* The CustomURLScheme class has a static method for adding cutom protocol
* handlers without getting bogged down with other class loaders and having to
* call setURLStreamHandlerFactory before the next guy...
*/
package com.cybernostics.lib.net.customurl;
import java.net.URLStreamHandler;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Allows you to add your own URL handler without running into problems
* of race conditions with setURLStream handler.
*
* To add your custom protocol eg myprot://blahblah:
*
* 1) Create a new protocol package which ends in myprot eg com.myfirm.protocols.myprot
* 2) Create a subclass of URLStreamHandler called Handler in this package
* 3) Before you use the protocol, call CustomURLScheme.add(com.myfirm.protocols.myprot.Handler.class);
* @author jasonw
*/
public class CustomURLScheme
{
// this is the package name required to implelent a Handler class
private static Pattern packagePattern = Pattern.compile( "(.+\\.protocols)\\.[^\\.]+" );
/**
* Call this method with your handlerclass
* @param handlerClass
* @throws Exception
*/
public static void add( Class<? extends URLStreamHandler> handlerClass ) throws Exception
{
if ( handlerClass.getSimpleName().equals( "Handler" ) )
{
String pkgName = handlerClass.getPackage().getName();
Matcher m = packagePattern.matcher( pkgName );
if ( m.matches() )
{
String protocolPackage = m.group( 1 );
add( protocolPackage );
}
else
{
throw new CustomURLHandlerException( "Your Handler class package must end in 'protocols.yourprotocolname' eg com.somefirm.blah.protocols.yourprotocol" );
}
}
else
{
throw new CustomURLHandlerException( "Your handler class must be called 'Handler'" );
}
}
private static void add( String handlerPackage )
{
// this property controls where java looks for
// stream handlers - always uses current value.
final String key = "java.protocol.handler.pkgs";
String newValue = handlerPackage;
if ( System.getProperty( key ) != null )
{
final String previousValue = System.getProperty( key );
newValue += "|" + previousValue;
}
System.setProperty( key, newValue );
}
}
CustomURLHandlerException.java:
/*
* Exception if you get things mixed up creating a custom url protocol
*/
package com.cybernostics.lib.net.customurl;
/**
*
* @author jasonw
*/
public class CustomURLHandlerException extends Exception
{
public CustomURLHandlerException(String msg )
{
super( msg );
}
}
I finally got it to work by running opening command line with "Run a Administrator" even though I was already admin and could create directory manually
If you get an error message like
An unhandled exception of type 'System.NullReferenceException' occurred in System.Windows.Forms.dll
if you work with SortableBindingList, your code probably uses some loops over DataGridView rows and also try to access the empty last row! (BindingSource = null)
If you don't need to allow the user to add new rows directly in the DataGridView this line of code easily solve the issue:
InitializeComponent();
m_dataGridView.AllowUserToAddRows = false; // after components initialized
...
As of 2016, you can do this more simply than in any of the answers already given:
$('#myChosenBox').val();
where "myChosenBox" is the id of the original select input. Or, in the change event:
$('#myChosenBox').on('change', function(e, params) {
alert(e.target.value); // OR
alert(this.value); // OR
alert(params.selected); // also in Panagiotis Kousaris' answer
}
In the Chosen doc, in the section near the bottom of the page on triggering events, it says "Chosen triggers a number of standard and custom events on the original select field." One of those standard events is the change event, so you can use it in the same way as you would with a standard select input. You don't have to mess around with using Chosen's applied classes as selectors if you don't want to. (For the change
event, that is. Other events are often a different matter.)
use the time and datetime packages.
if anybody want to execute this script and also find out how much time it took to execute in minutes
import time
from time import strftime
from datetime import datetime
from time import gmtime
def start_time_():
#import time
start_time = time.time()
return(start_time)
def end_time_():
#import time
end_time = time.time()
return(end_time)
def Execution_time(start_time_,end_time_):
#import time
#from time import strftime
#from datetime import datetime
#from time import gmtime
return(strftime("%H:%M:%S",gmtime(int('{:.0f}'.format(float(str((end_time-start_time))))))))
start_time = start_time_()
# your code here #
[i for i in range(0,100000000)]
# your code here #
end_time = end_time_()
print("Execution_time is :", Execution_time(start_time,end_time))
The above code works for me. I hope this helps.
You may use Json.Net framework to do this. Just like this :
Account account = JsonConvert.DeserializeObject<Account>(json);
the home page : http://json.codeplex.com/
the document about this : http://james.newtonking.com/json/help/index.html#
Look for an installation subdirectory, likely named eclipse. Under that subdirectory, if you see files like eclipse.ini, icon.xpm and subdirectories like plugins and dropins, remove the subdirectory parent (the one named eclipse).
That will remove your installation except for anything you've set up yourself (like workspaces, projects, etc.).
Hope this helps.
awk works well if you your server has it
var="text,text,text,text"
num=$(echo "${var}" | awk -F, '{print NF-1}')
echo "${num}"
Here is one that works better for me (LINQPad version):
DateTime d;
DateTime.TryParseExact(
"2010-08-20T15:00:00Z",
@"yyyy-MM-dd\THH:mm:ss\Z",
CultureInfo.InvariantCulture,
DateTimeStyles.AssumeUniversal,
out d);
d.ToString()
produces
true
8/20/2010 8:00:00 AM
Gilean's answer is great, but I just wanted to add that sometimes there are rare exceptions to best practices, and you might want to test your environment both ways to see what will work best.
In one case, I found that query
worked faster for my purposes because I was bulk transferring trusted data from an Ubuntu Linux box running PHP7 with the poorly supported Microsoft ODBC driver for MS SQL Server.
I arrived at this question because I had a long running script for an ETL that I was trying to squeeze for speed. It seemed intuitive to me that query
could be faster than prepare
& execute
because it was calling only one function instead of two. The parameter binding operation provides excellent protection, but it might be expensive and possibly avoided if unnecessary.
Given a couple rare conditions:
If you can't reuse a prepared statement because it's not supported by the Microsoft ODBC driver.
If you're not worried about sanitizing input and simple escaping is acceptable. This may be the case because binding certain datatypes isn't supported by the Microsoft ODBC driver.
PDO::lastInsertId
is not supported by the Microsoft ODBC driver.
Here's a method I used to test my environment, and hopefully you can replicate it or something better in yours:
To start, I've created a basic table in Microsoft SQL Server
CREATE TABLE performancetest (
sid INT IDENTITY PRIMARY KEY,
id INT,
val VARCHAR(100)
);
And now a basic timed test for performance metrics.
$logs = [];
$test = function (String $type, Int $count = 3000) use ($pdo, &$logs) {
$start = microtime(true);
$i = 0;
while ($i < $count) {
$sql = "INSERT INTO performancetest (id, val) OUTPUT INSERTED.sid VALUES ($i,'value $i')";
if ($type === 'query') {
$smt = $pdo->query($sql);
} else {
$smt = $pdo->prepare($sql);
$smt ->execute();
}
$sid = $smt->fetch(PDO::FETCH_ASSOC)['sid'];
$i++;
}
$total = (microtime(true) - $start);
$logs[$type] []= $total;
echo "$total $type\n";
};
$trials = 15;
$i = 0;
while ($i < $trials) {
if (random_int(0,1) === 0) {
$test('query');
} else {
$test('prepare');
}
$i++;
}
foreach ($logs as $type => $log) {
$total = 0;
foreach ($log as $record) {
$total += $record;
}
$count = count($log);
echo "($count) $type Average: ".$total/$count.PHP_EOL;
}
I've played with multiple different trial and counts in my specific environment, and consistently get between 20-30% faster results with query
than prepare
/execute
5.8128969669342 prepare
5.8688418865204 prepare
4.2948560714722 query
4.9533629417419 query
5.9051351547241 prepare
4.332102060318 query
5.9672858715057 prepare
5.0667371749878 query
3.8260300159454 query
4.0791549682617 query
4.3775160312653 query
3.6910600662231 query
5.2708210945129 prepare
6.2671611309052 prepare
7.3791449069977 prepare
(7) prepare Average: 6.0673267160143
(8) query Average: 4.3276024162769
I'm curious to see how this test compares in other environments, like MySQL.
I like your server side idea, even if my proposed implementation of it sounds a little bit ghetto.
You could set the .innerHTML of the iframe to the HTML contents you grab server side. Depending on how you grab this, you will have to pay attention to relative versus absolute paths.
Plus, depending on how the page you are grabbing interacts with other pages, this could totally not work (cookies being set for the page you are grabbing won't work across domains, maybe state is being tracked in Javascript... Lots of reasons this might not work.)
I don't believe that tracking the current state of the page you are trying to mirror is theoretically possible, but I'm not sure. The site could track all sorts of things server side, you won't have access to this state. Imagine the case where on a page load a variable is set to a random value server-side, how would you capture this state?
Do these ideas help with anything?
-Brian J. Stinar-
on mac terminal (at least in ZSH): open stackoverflow.com
(opens site in new tab in your chrome default browser)
If is a package then you can get the source for that with:
select text from all_source where name = 'PADCAMPAIGN'
and type = 'PACKAGE BODY'
order by line;
Oracle doesn't store the source for a sub-program separately, so you need to look through the package source for it.
Note: I've assumed you didn't use double-quotes when creating that package, but if you did , then use
select text from all_source where name = 'pAdCampaign'
and type = 'PACKAGE BODY'
order by line;
I had the same issue with firefox, when I searched for a solution I didn't find anything, but then I tried to load the script from a cdn, it worked properly, so I think you should try loading it from a cdn link, I mean if you are trying to load a script that you havn't created. because in my case, when tried to load a script that is mine, it worked and imported successfully, for now I don't know why, but I think there is something in the scripts from network, so just try cdn, you won't lose anything.
I wish it help you.
If not HTML
, then UTF-8
is not recommended. koi8-r
and windows-1251
only without problems. So use html mail.
$headers['Content-Type']='text/html; charset=UTF-8';
$body='<html><head><meta charset="UTF-8"><title>ESP Notufy - ESP ?????????</title></head><body>'.$text.'</body></html>';
$mail_object=& Mail::factory('smtp',
array ('host' => $host,
'auth' => true,
'username' => $username,
'password' => $password));
$mail_object->send($recipents, $headers, $body);
}
You can use click touchend
,
example:
$('a').on('click touchend', function() {
var linkToAffect = $(this);
var linkToAffectHref = linkToAffect.attr('href');
window.location = linkToAffectHref;
});
Above example will affect all links on touch devices.
If you want to target only specific links, you can do this by setting a class on them, ie:
HTML:
<a href="example.html" class="prevent-extra-click">Prevent extra click on touch device</a>
Jquery:
$('a.prevent-extra-click').on('click touchend', function() {
var linkToAffect = $(this);
var linkToAffectHref = linkToAffect.attr('href');
window.location = linkToAffectHref;
});
Cheers,
Jeroen
Essentially the only way to deal with this is to have a webserver running on localhost and to serve them from there.
It is insecure for a browser to allow an ajax request to access any file on your computer, therefore most browsers seem to treat "file://" requests as having no origin for the purpose of "Same Origin Policy"
Starting a webserver can be as trivial as cd
ing into the directory the files are in and running:
python -m SimpleHTTPServer