Spinlock and Mutex synchronization mechanisms are very common today to be seen.
Let's think about Spinlock first.
Basically it is a busy waiting action, which means that we have to wait for a specified lock is released before we can proceed with the next action. Conceptually very simple, while implementing it is not on the case. For example: If the lock has not been released then the thread was swap-out and get into the sleep state, should do we deal with it? How to deal with synchronization locks when two threads simultaneously request access ?
Generally, the most intuitive idea is dealing with synchronization via a variable to protect the critical section. The concept of Mutex is similar, but they are still different. Focus on: CPU utilization. Spinlock consumes CPU time to wait for do the action, and therefore, we can sum up the difference between the two:
In homogeneous multi-core environments, if the time spend on critical section is small than use Spinlock, because we can reduce the context switch time. (Single-core comparison is not important, because some systems implementation Spinlock in the middle of the switch)
In Windows, using Spinlock will upgrade the thread to DISPATCH_LEVEL, which in some cases may be not allowed, so this time we had to use a Mutex (APC_LEVEL).
You must have some virtual function declared in one of the parent classes and never implemented in any of the child classes. Make sure that all virtual functions are implemented somewhere in the inheritence chain. If a class's definition includes a pure virtual function that is never implemented, an instance of that class cannot ever be constructed.
war - web archive. It is used to deploy web applications according to the servlet standard. It is a jar file containing a special directory called WEB-INF and several files and directories inside it (web.xml, lib, classes) as well as all the HTML, JSP, images, CSS, JavaScript and other resources of the web application
ear - enterprise archive. It is used to deploy enterprise application containing EJBs, web applications, and 3rd party libraries. It is also a jar file, it has a special directory called APP-INF that contains the application.xml file, and it contains jar and war files.
Another solution is passing the read function to the constructor of Readable (cf doc stream readeable options)
var s = new Readable({read(size) {
this.push("your string here")
this.push(null)
}});
you can after use s.pipe for exemple
You can write update statement for one table and then a trigger on first table update, which update second table
In my case, I needed to specify a viahost
and viauser
. Worth trying if you're in a complex system. :)
I create a file dif.go
that contains your code:
package dif
import (
"time"
)
var StartTime = time.Now()
Outside the folder I create my main.go
, it is ok!
package main
import (
dif "./dif"
"fmt"
)
func main() {
fmt.Println(dif.StartTime)
}
Outputs:
2016-01-27 21:56:47.729019925 +0800 CST
Files directory structure:
folder
main.go
dif
dif.go
It works!
After a bunch of installing and uninstalling of Postgres, here's what now seems to work consistently for me with Os X Mavericks, Rails 4 and Ruby 2.
In the database.yml file, I change the default usernames to my computer's username which for me is just "admin".
In the command line I run rake db:create:all
Then I run rake db:migrate
When I run the rails server and check the local host it says "Welcome aboard".
Basically you need following things to make location detector android app
Now if you write each of these module yourself then it needs much time and efforts. So it would be better to use ready resources that are being maintained already.
Using all these resources, you will be able to create an flawless android location detection app.
You will first need to listen for current location of user. You can use any of below libraries to quick start.
This library provide last known location, location updates
With this library you just need to provide a Configuration object with your requirements, and you will receive a location or a fail reason with all the stuff are described above handled.
Use this open source repo of the Hypertrack Live app to build live location sharing experience within your app within a few hours. HyperTrack Live app helps you share your Live Location with friends and family through your favorite messaging app when you are on the way to meet up. HyperTrack Live uses HyperTrack APIs and SDKs.
Google Maps Android API utility library
If you want to add route maps feature in your apps you can use DrawRouteMaps to make you work more easier. This is lib will help you to draw route maps between two point LatLng.
Simple, smooth animation for route / polylines on google maps using projections. (WIP)
This project allows you to calculate the direction between two locations and display the route on a Google Map using the Google Directions API.
This will solve my “SMTP Error: Could not authenticate” in PHPMailer error.
Aggregation vs Composition
Aggregation implies a relationship where the child can exist independently of the parent. For example, Bank and Employee, delete the Bank and the Employee still exist.
whereas Composition implies a relationship where the child cannot exist independent of the parent. Example: Human and heart, heart don’t exist separate to a Human.
Aggregation relation is “has-a” and composition is “part-of” relation.
Composition is a strong Association whereas Aggregation is a weak Association.
Building on @Rob Neild's answer above, here is a pure JS adaptation that returns a simple object of decoded query string params (no %20's, etc).
function parseQueryString () {
var parsedParameters = {},
uriParameters = location.search.substr(1).split('&');
for (var i = 0; i < uriParameters.length; i++) {
var parameter = uriParameters[i].split('=');
parsedParameters[parameter[0]] = decodeURIComponent(parameter[1]);
}
return parsedParameters;
}
I know the topic is a bit old and seems stale, but anyway I was able to use these options:
deploy:
resources:
limits:
cpus: '0.001'
memory: 50M
when using 3.7 version of docker-compose
What helped in my case, was using this command:
docker-compose --compatibility up
--compatibility
flag stands for (taken from the documentation):
If set, Compose will attempt to convert deploy keys in v3 files to their non-Swarm equivalent
Think it's great, that I don't have to revert my docker-compose file back to v2.
I think Gumbo's answer is just fine. Some people prefer this fancy expression that does the same thing:
$int = (($int > 0) ? -$int : $int);
EDIT: Apparently you are looking for a function that will make negatives positive as well. I think these answers are the simplest:
/* I am not proposing you actually use functions called
"makeNegative" and "makePositive"; I am just presenting
the most direct solution in the form of two clearly named
functions. */
function makeNegative($num) { return -abs($num); }
function makePositive($num) { return abs($num); }
Here is the official document about uninstalling the JDK.
http://docs.oracle.com/javase/8/docs/technotes/guides/install/mac_jdk.html#A1096903
I solved the problem by changing the compileSdkVersion
in the Gradle.build file from 18 to 17.
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:0.5.+'
}
}
apply plugin: 'android'
repositories {
mavenCentral()
}
android {
compileSdkVersion 17
buildToolsVersion "17.0.0"
defaultConfig {
minSdkVersion 10
targetSdkVersion 18
}
}
dependencies {
compile 'com.android.support:support-v4:13.0.+'
}
IMHO JSmooth seems to do a pretty good job.
If file really exists and you want to replace it use below code:
string file = "c:\test\SomeFile.txt"
string moveTo = "c:\test\test\SomeFile.txt"
if (File.Exists(moveTo))
{
File.Delete(moveTo);
}
File.Move(file, moveTo);
REST is tightly coupled with HTTP, so if you only expose your API over HTTP then REST is more appropriate for most (but not all) situations. However, if you need to expose your API over other transports like messaging or web sockets then REST is just not applicable.
You can write the where
clause as:
where (case when (:stateCode = '') then (1)
when (:stateCode != '') and (vw.state_cd in (:stateCode)) then 1
else 0)
end) = 1;
Alternatively, remove the case
entirely:
where (:stateCode = '') or
((:stateCode != '') and vw.state_cd in (:stateCode));
Or, even better:
where (:stateCode = '') or vw.state_cd in (:stateCode)
As others mentioned, you could use JDialog. If you don't have access to the parent frame or you want to freeze the hole application just pass null as a parent:
final JDialog frame = new JDialog((JFrame)null, frameTitle, true);
frame.setModal(true);
frame.getContentPane().add(panel);
frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
frame.pack();
frame.setVisible(true);
Here is a alternative solution in Python 3.0 which allows non-string list items:
>>> alist = ['a', 1, (2, 'b')]
a standard way
>>> ", ".join(map(str, alist))
"a, 1, (2, 'b')"
the alternative solution
>>> import io
>>> s = io.StringIO()
>>> print(*alist, file=s, sep=', ', end='')
>>> s.getvalue()
"a, 1, (2, 'b')"
NOTE: The space after comma is intentional.
Try \r\n
where \r
is carriage return. Also ensure that your output do not have new line, because debugger can show you special characters in form of \n
, \r
, \t
etc.
for i in range(len(Data)):
Data[i, 1] = Data[i-lookback:i, 0].sum() / lookback
Try this piece of code. I think it's simpler and does the job. lookback is the window of the moving average.
In the Data[i-lookback:i, 0].sum()
I have put 0
to refer to the first column of the dataset but you can put any column you like in case you have more than one column.
You can use AngularJs for this, Its two -way data binding feature will get solution with minimum effort and less code.
<div>
<input type="text" name="" ng-model="fbid"><br/>
<img src="https://graph.facebook.com/{{fbid}}/picture?type=normal">
</div>
I hope this answers your query.Note: You can use other library as well.
In addition (or in replacement) to the HTML5's <a download
attribute already mentioned,
the browser's download to disk behavior can also be triggered by the following http response header:
Content-Disposition: attachment; filename=ProposedFileName.txt;
This was the way to do before HTML5 (and still works with browsers supporting HTML5).
Use DATESTR
>> datestr(40189)
ans =
12-Jan-0110
Unfortunately, Excel starts counting at 1-Jan-1900. Find out how to convert serial dates from Matlab to Excel by using DATENUM
>> datenum(2010,1,11)
ans =
734149
>> datenum(2010,1,11)-40189
ans =
693960
>> datestr(40189+693960)
ans =
11-Jan-2010
In other words, to convert any serial Excel date, call
datestr(excelSerialDate + 693960)
EDIT
To get the date in mm/dd/yyyy format, call datestr
with the specified format
excelSerialDate = 40189;
datestr(excelSerialDate + 693960,'mm/dd/yyyy')
ans =
01/11/2010
Also, if you want to get rid of the leading zero for the month, you can use REGEXPREP to fix things
excelSerialDate = 40189;
regexprep(datestr(excelSerialDate + 693960,'mm/dd/yyyy'),'^0','')
ans =
1/11/2010
Try:
To_Date (SESSION_START_DATE_TIME, 'MM/DD/YYYY hh24:mi') >
To_Date ('12-Jan-2012 16:00', 'DD-MON-YYYY hh24:mi' )
Just use Double.compare() method to compare double values.
Double.compare((d1,d2) == 0)
double d1 = 0.0;
double d2 = 0.0;
System.out.println(Double.compare((d1,d2) == 0)) // true
There is no tool specifically in the 'setup.exe' installer that offers the functionality of apt-get. There is, however, a command-line package installer for Cygwin that can be downloaded separately, but it is not entirely stable and relies on workarounds.
apt-cyg: http://github.com/transcode-open/apt-cyg
Check out the issues tab for the project to see the known problems.
As @Awe had said above, this is the solution, that is confirmed to work in Chrome!!
Just make sure this is INSIDE the head tags:
<head>
<style media="print">
@page
{
size: auto; /* auto is the initial value */
margin: 0mm; /* this affects the margin in the printer settings */
}
body
{
background-color:#FFFFFF;
border: solid 1px black ;
margin: 0px; /* this affects the margin on the content before sending to printer */
}
</style>
</head>
Thank you Rob W for your answer.
I have been using this within a Cordova application to avoid having to load the API and so that I can easily control iframes which are loaded dynamically.
I always wanted the ability to be able to extract information from the iframe, such as the state (getPlayerState) and the time (getCurrentTime).
Rob W helped highlight how the API works using postMessage, but of course this only sends information in one direction, from our web page into the iframe. Accessing the getters requires us to listen for messages posted back to us from the iframe.
It took me some time to figure out how to tweak Rob W's answer to activate and listen to the messages returned by the iframe. I basically searched through the source code within the YouTube iframe until I found the code responsible for sending and receiving messages.
The key was changing the 'event' to 'listening', this basically gave access to all the methods which were designed to return values.
Below is my solution, please note that I have switched to 'listening' only when getters are requested, you can tweak the condition to include extra methods.
Note further that you can view all messages sent from the iframe by adding a console.log(e) to the window.onmessage. You will notice that once listening is activated you will receive constant updates which include the current time of the video. Calling getters such as getPlayerState will activate these constant updates but will only send a message involving the video state when the state has changed.
function callPlayer(iframe, func, args) {
iframe=document.getElementById(iframe);
var event = "command";
if(func.indexOf('get')>-1){
event = "listening";
}
if ( iframe&&iframe.src.indexOf('youtube.com/embed') !== -1) {
iframe.contentWindow.postMessage( JSON.stringify({
'event': event,
'func': func,
'args': args || []
}), '*');
}
}
window.onmessage = function(e){
var data = JSON.parse(e.data);
data = data.info;
if(data.currentTime){
console.log("The current time is "+data.currentTime);
}
if(data.playerState){
console.log("The player state is "+data.playerState);
}
}
I ran into a similar issue where eclipse was not using my current %JAVA_HOME%
that was on the path
and was instead using an older version. The documentation points out that if no -vm
is specified in the ini file, eclipse will search for a shared library jvm.dll
This appears in the registry under the key HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\JavaSoft\Java Runtime Environment
that gets installed when using the windows java installer (key might be a bit different based on 64-bit vs 32-bit, but search for jvm.dll
). Because it was finding this shared library on my path
before the %JAVA_HOME%/bin
, it was using the old version.
Like others have stated, the easiest way to deal with this is to specify the specific vm you want to use in the eclipse.ini
file. I'm writing this because I couldn't figure out how it was still using the old version when it wasn't specified anywhere on the path
or eclipse.ini
file.
See link to doc below: http://help.eclipse.org/kepler/topic/org.eclipse.platform.doc.isv/reference/misc/launcher.html?cp=2_1_3_1
Finding a VM and using the JNI Invocation API
The Eclipse launcher is capable of loading the Java VM in the eclipse process using the Java Native Interface Invocation API. The launcher is still capable of starting the Java VM in a separate process the same as previous version of Eclipse did. Which method is used depends on how the VM was found.
No -vm specified
When no -vm is specified, the launcher looks for a virtual machine first in a jre directory in the root of eclipse and then on the search path. If java is found in either location, then the launcher looks for a jvm shared library (jvm.dll on Windows, libjvm.so on *nix platforms) relative to that java executable.
- If a jvm shared library is found the launcher loads it and uses the JNI invocation API to start the vm.
- If no jvm shared library is found, the launcher executes the java launcher to start the vm in a new process.
-vm specified on the command line or in eclipse.ini
Eclipse can be started with "-vm " to indicate a virtual machine to use. There are several possibilities for the value of :
- directory: is a directory. We look in that directory for:
- (1) a java launcher or
- (2) the jvm shared library.
If we find the jvm shared library, we use JNI invocation. If we find a launcher, we attempt to find a jvm library in known locations relative to the launcher. If we find one, we use JNI invocation. If no jvm library is found, we exec java in a new process.
java.exe/javaw.exe: is a path to a java launcher. We exec that java launcher to start the vm in a new process.
jvm dll or so: is a path to a jvm shared library. We attempt to load that library and use the JNI Invocation API to start the vm in the current process.
try this..
SELECT Name
FROM sys.procedures
WHERE OBJECT_DEFINITION(OBJECT_ID) LIKE '%CreatedDate%'
GO
or you can generate a scripts of all procedures and search from there.
If you want to find the rows
that have any of the values in a vector, one option is to loop the vector (lapply(v1,..)
), create a logical index of (TRUE/FALSE) with (==
). Use Reduce
and OR (|
) to reduce the list to a single logical matrix by checking the corresponding elements. Sum the rows (rowSums
), double negate (!!
) to get the rows with any matches.
indx1 <- !!rowSums(Reduce(`|`, lapply(v1, `==`, df)), na.rm=TRUE)
Or vectorise and get the row indices with which
with arr.ind=TRUE
indx2 <- unique(which(Vectorize(function(x) x %in% v1)(df),
arr.ind=TRUE)[,1])
I didn't use @kristang's solution as it is giving me errors. Based on a 1000x500
matrix, @konvas's solution is the most efficient (so far). But, this may vary if the number of rows are increased
val <- paste0('M0', 1:1000)
set.seed(24)
df1 <- as.data.frame(matrix(sample(c(val, NA), 1000*500,
replace=TRUE), ncol=500), stringsAsFactors=FALSE)
set.seed(356)
v1 <- sample(val, 200, replace=FALSE)
konvas <- function() {apply(df1, 1, function(r) any(r %in% v1))}
akrun1 <- function() {!!rowSums(Reduce(`|`, lapply(v1, `==`, df1)),
na.rm=TRUE)}
akrun2 <- function() {unique(which(Vectorize(function(x) x %in%
v1)(df1),arr.ind=TRUE)[,1])}
library(microbenchmark)
microbenchmark(konvas(), akrun1(), akrun2(), unit='relative', times=20L)
#Unit: relative
# expr min lq mean median uq max neval
# konvas() 1.00000 1.000000 1.000000 1.000000 1.000000 1.00000 20
# akrun1() 160.08749 147.642721 125.085200 134.491722 151.454441 52.22737 20
# akrun2() 5.85611 5.641451 4.676836 5.330067 5.269937 2.22255 20
# cld
# a
# b
# a
For ncol = 10
, the results are slighjtly different:
expr min lq mean median uq max neval
konvas() 3.116722 3.081584 2.90660 2.983618 2.998343 2.394908 20
akrun1() 27.587827 26.554422 22.91664 23.628950 21.892466 18.305376 20
akrun2() 1.000000 1.000000 1.00000 1.000000 1.000000 1.000000 20
v1 <- c('M017', 'M018')
df <- structure(list(datetime = c("04.10.2009 01:24:51",
"04.10.2009 01:24:53",
"04.10.2009 01:24:54", "04.10.2009 01:25:06", "04.10.2009 01:25:07",
"04.10.2009 01:26:07", "04.10.2009 01:26:27", "04.10.2009 01:27:23",
"04.10.2009 01:27:30", "04.10.2009 01:27:32", "04.10.2009 01:27:34"
), col1 = c("M017", "M018", "M051", "<NA>", "<NA>", "<NA>", "<NA>",
"<NA>", "<NA>", "M017", "M051"), col2 = c("<NA>", "<NA>", "<NA>",
"M016", "M015", "M017", "M017", "M017", "M017", "<NA>", "<NA>"
), col3 = c("<NA>", "<NA>", "<NA>", "<NA>", "<NA>", "<NA>", "<NA>",
"<NA>", "<NA>", "<NA>", "<NA>"), col4 = c(NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA)), .Names = c("datetime", "col1", "col2",
"col3", "col4"), class = "data.frame", row.names = c("1", "2",
"3", "4", "5", "6", "7", "8", "9", "10", "11"))
If you're looking to simply reduce or increase the width of Bootstrap's input elements to your liking, I would use max-width
in the CSS.
Here is a very simple example I created:
<form style="max-width:500px">
<div class="form-group">
<input type="text" class="form-control" id="name" placeholder="Name">
</div>
<div class="form-group">
<input type="email" class="form-control" id="email" placeholder="Email Address">
</div>
<div class="form-group">
<textarea class="form-control" rows="5" placeholder="Message"></textarea>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
I've set the whole form's maximum width to 500px. This way you won't need to use any of Bootstrap's grid system and it will also keep the form responsive.
For Android Kotlin users:
"#FFF".longARGB()?.let{ Color.parceColor(it) }
"#FFFF".longARGB()?.let{ Color.parceColor(it) }
fun String?.longARGB(): String? {
if (this == null || !startsWith("#")) return null
// #RRGGBB or #AARRGGBB
if (length == 7 || length == 9) return this
// #RGB or #ARGB
if (length in 4..5) {
val rgb = "#${this[1]}${this[1]}${this[2]}${this[2]}${this[3]}${this[3]}"
if (length == 5) {
return "$rgb${this[4]}${this[4]}"
}
return rgb
}
return null
}
Here is my version. It shows only as much as necessary, handles pluralization, negatives, and I tried to make it lightweight.
0 seconds
1.404 seconds
1 hour, 14.4 seconds
14 hours, 57 minutes, 22.473 seconds
1 day, 14 hours, 57 minutes, 22.475 seconds
public static class TimeSpanExtensions
{
public static string ToReadableString(this TimeSpan timeSpan)
{
int days = (int)(timeSpan.Ticks / TimeSpan.TicksPerDay);
long subDayTicks = timeSpan.Ticks % TimeSpan.TicksPerDay;
bool isNegative = false;
if (timeSpan.Ticks < 0L)
{
isNegative = true;
days = -days;
subDayTicks = -subDayTicks;
}
int hours = (int)((subDayTicks / TimeSpan.TicksPerHour) % 24L);
int minutes = (int)((subDayTicks / TimeSpan.TicksPerMinute) % 60L);
int seconds = (int)((subDayTicks / TimeSpan.TicksPerSecond) % 60L);
int subSecondTicks = (int)(subDayTicks % TimeSpan.TicksPerSecond);
double fractionalSeconds = (double)subSecondTicks / TimeSpan.TicksPerSecond;
var parts = new List<string>(4);
if (days > 0)
parts.Add(string.Format("{0} day{1}", days, days == 1 ? null : "s"));
if (hours > 0)
parts.Add(string.Format("{0} hour{1}", hours, hours == 1 ? null : "s"));
if (minutes > 0)
parts.Add(string.Format("{0} minute{1}", minutes, minutes == 1 ? null : "s"));
if (fractionalSeconds.Equals(0D))
{
switch (seconds)
{
case 0:
// Only write "0 seconds" if we haven't written anything at all.
if (parts.Count == 0)
parts.Add("0 seconds");
break;
case 1:
parts.Add("1 second");
break;
default:
parts.Add(seconds + " seconds");
break;
}
}
else
{
parts.Add(string.Format("{0}{1:.###} seconds", seconds, fractionalSeconds));
}
string resultString = string.Join(", ", parts);
return isNegative ? "(negative) " + resultString : resultString;
}
}
The problem is that some versions of explorer don't support the window.open javascript function
Say what? Can you provide a reference for that statement? With respect, I think you must be mistaken. This works on IE6 and IE9, for instance.
Most modern browsers won't let your code use window.open
except in direct response to a user event, in order to keep spam pop-ups and such at bay; perhaps that's what you're thinking of. As long as you only use window.open
when responding to a user event, you should be fine using window.open
— with all versions of IE.
There is no way to use location
to open a new window. Just window.open
or, of course, the user clicking a link with target="_blank"
.
UPDATE test SET a = CONCAT(a, "more text")
Here's what worked for me. Note: Adding the image within a row introduces some space so I've intentionally used only a div to encapsulate the image.
<div class="container-fluid w-100 h-auto m-0 p-0">
<img src="someimg.jpg" class="img-fluid w-100 h-auto p-0 m-0" alt="Patience">
</div>
BASEPAIRS = { "T": "A", "A": "T", "G": "C", "C": "G" } What would you use?
Maybe:
static const char basepairs[] = "ATAGCG";
// lookup:
if (const char* p = strchr(basepairs, c))
// use p[1]
;-)
If that number represents milliseconds, use the Date's constructor :
var myDate = new Date(1238540400000);
There are references to the official docs (DialogFragment Reference) in other answers, but no mention of the example given there:
void showDialog() {
mStackLevel++;
// DialogFragment.show() will take care of adding the fragment
// in a transaction. We also want to remove any currently showing
// dialog, so make our own transaction and take care of that here.
FragmentTransaction ft = getFragmentManager().beginTransaction();
Fragment prev = getFragmentManager().findFragmentByTag("dialog");
if (prev != null) {
ft.remove(prev);
}
ft.addToBackStack(null);
// Create and show the dialog.
DialogFragment newFragment = MyDialogFragment.newInstance(mStackLevel);
newFragment.show(ft, "dialog");
}
This removes any currently shown dialog, creates a new DialogFragment with an argument, and shows it as a new state on the back stack. When the transaction is popped, the current DialogFragment and its Dialog will be destroyed, and the previous one (if any) re-shown. Note that in this case DialogFragment will take care of popping the transaction of the Dialog is dismissed separately from it.
For my needs I changed it to:
FragmentManager manager = getSupportFragmentManager();
Fragment prev = manager.findFragmentByTag(TAG);
if (prev != null) {
manager.beginTransaction().remove(prev).commit();
}
MyDialogFragment fragment = new MyDialogFragment();
fragment.show(manager, TAG);
I generally first try .inspect
, if that doesn't give me what I want, I'll switch to .to_yaml
.
class User
attr_accessor :name, :age
end
user = User.new
user.name = "John Smith"
user.age = 30
puts user.inspect
#=> #<User:0x423270c @name="John Smith", @age=30>
puts user.to_yaml
#=> --- !ruby/object:User
#=> age: 30
#=> name: John Smith
Hope that helps.
Make it
float b= 3.6f;
A floating-point literal is of type float if it is suffixed with an ASCII letter F or f; otherwise its type is double and it can optionally be suffixed with an ASCII letter D or d
You do not need to use an anonymous function with setTimeout
. You can do something like this:
setTimeout(doSomething, 3000);
function doSomething() {
//do whatever you want here
}
The simple answer (in MVC 3 onwards, maybe even 2) is you don't have to do anything special.
As long as your JSON parameters match the model, MVC is smart enough to construct a new object from the parameters you give it. The parameters that aren't there are just defaulted.
For example, the Javascript:
var values =
{
"Name": "Chris",
"Color": "Green"
}
$.post("@Url.Action("Update")",values,function(data)
{
// do stuff;
});
The model:
public class UserModel
{
public string Name { get;set; }
public string Color { get;set; }
public IEnumerable<string> Contacts { get;set; }
}
The controller:
public ActionResult Update(UserModel model)
{
// do something with the model
return Json(new { success = true });
}
You can use : Query grouping allows you to create groups of WHERE clauses by enclosing them in parentheses. This will allow you to create queries with complex WHERE clauses. Nested groups are supported. Example:
$this->db->select('*')->from('my_table')
->group_start()
->where('a', 'a')
->or_group_start()
->where('b', 'b')
->where('c', 'c')
->group_end()
->group_end()
->where('d', 'd')
->get();
https://www.codeigniter.com/userguide3/database/query_builder.html#query-grouping
(function($){
$.click2 = function (elm, o){
this.ao = o;
var DELAY = 700, clicks = 0;
var timer = null;
var self = this;
$(elm).on('click', function(e){
clicks++;
if(clicks === 1){
timer = setTimeout(function(){
self.ao.click(e);
}, DELAY);
} else {
clearTimeout(timer);
self.ao.dblclick(e);
}
}).on('dblclick', function(e){
e.preventDefault();
});
};
$.click2.defaults = { click: function(e){}, dblclick: function(e){} };
$.fn.click2 = function(o){
o = $.extend({},$.click2.defaults, o);
this.each(function(){ new $.click2(this, o); });
return this;
};
})(jQuery);
And finally we use as.
$("a").click2({
click : function(e){
var cid = $(this).data('cid');
console.log("Click : "+cid);
},
dblclick : function(e){
var cid = $(this).data('cid');
console.log("Double Click : "+cid);
}
});
This is because images
and tmp_file_upload
are only writable by root
user. For upload to work we need to make the owner of those folders same as httpd process owner OR make them globally writable (bad practice).
$ps aux | grep httpd
. The first column will be the owner typically it will be nobody
Change the owner of images
and tmp_file_upload
to be become nobody
or whatever the owner you found in step 1.
$sudo chown nobody /var/www/html/mysite/images/
$sudo chown nobody /var/www/html/mysite/tmp_file_upload/
Chmod images
and tmp_file_upload
now to be writable by the owner, if needed [Seems you already have this in place]. Mentioned in @Dmitry Teplyakov answer.
$ sudo chmod -R 0755 /var/www/html/mysite/images/
$ sudo chmod -R 0755 /var/www/html/mysite/tmp_file_upload/
For more details why this behavior happend, check the manual http://php.net/manual/en/ini.core.php#ini.upload-tmp-dir , note that it also talking about open_basedir
directive.
IF exists
IF exists (select * from table_1 where col1 = 'value')
BEGIN
-- one or more
insert into table_1 (col1) values ('valueB')
END
ELSE
-- zero
insert into table_1 (col1) values ('value')
In your project parent directory, run:
git submodule update --init
Or if you have recursive submodules run:
git submodule update --init --recursive
Sometimes this still doesn't work, because somehow you have local changes in the local submodule directory while the submodule is being updated.
Most of the time the local change might not be the one you want to commit. It can happen due to a file deletion in your submodule, etc. If so, do a reset in your local submodule directory and in your project parent directory, run again:
git submodule update --init --recursive
select * from my_table where my_field Like '[a-z][a-z]%'
Alternatively you can do it in one line (tested in win10)
sqlite3 -help
sqlite3 -header -csv db.sqlite 'select * from tbl1;' > test.csv
Bonus: Using powershell with cmdlet and pipe (|).
get-content query.sql | sqlite3 -header -csv db.sqlite > test.csv
where query.sql is a file containing your SQL query
dataGridView1.EnableHeadersVisualStyles = false;
dataGridView1.ColumnHeadersDefaultCellStyle.BackColor = Color.Blue;
The conversion to list
that's been suggested in the other answers is the best way if you still want to process the generator elements afterwards, but has one flaw: It uses O(n) memory. You can count the elements in a generator without using that much memory with:
sum(1 for x in generator)
Of course, be aware that this might be slower than len(list(generator))
in common Python implementations, and if the generators are long enough for the memory complexity to matter, the operation would take quite some time. Still, I personally prefer this solution as it describes what I want to get, and it doesn't give me anything extra that's not required (such as a list of all the elements).
Also listen to delnan's advice: If you're discarding the output of the generator it is very likely that there is a way to calculate the number of elements without running it, or by counting them in another manner.
You only need to worry about using physically contiguous memory if the buffer will be accessed by a DMA device on a physically addressed bus (like PCI). The trouble is that many system calls have no way to know whether their buffer will eventually be passed to a DMA device: once you pass the buffer to another kernel subsystem, you really cannot know where it is going to go. Even if the kernel does not use the buffer for DMA today, a future development might do so.
vmalloc is often slower than kmalloc, because it may have to remap the buffer space into a virtually contiguous range. kmalloc never remaps, though if not called with GFP_ATOMIC kmalloc can block.
kmalloc is limited in the size of buffer it can provide: 128 KBytes*). If you need a really big buffer, you have to use vmalloc or some other mechanism like reserving high memory at boot.
*) This was true of earlier kernels. On recent kernels (I tested this on 2.6.33.2), max size of a single kmalloc is up to 4 MB! (I wrote a fairly detailed post on this.) — kaiwan
For a system call you don't need to pass GFP_ATOMIC to kmalloc(), you can use GFP_KERNEL. You're not an interrupt handler: the application code enters the kernel context by means of a trap, it is not an interrupt.
Found the solution as below.... posting it as it could help somebody else too :)
DateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date date = format.parse("2014-04-24 11:15:00");
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(date);
XMLGregorianCalendar xmlGregCal = DatatypeFactory.newInstance().newXMLGregorianCalendar(cal);
System.out.println(xmlGregCal);
Output:
2014-04-24T11:15:00.000+02:00
There are several reasons you could have problems loading from lib - see here for details - http://www.williambharding.com/blog/technology/rails-3-autoload-modules-and-classes-in-production/
In Windows 10 I browsed to *%APPDATA%\MySQL\Workbench* then deleted the workbench_user_data.dat file
Doing so lost my MySqlWorkbence settings but allowed MySqlWorkbence to open.
split("(?!^)")
does not work correctly if the string contains surrogate pairs. You should use split("(?<=.)")
.
String[] splitted = "?ab".split("(?<=.)");
System.out.println(Arrays.toString(splitted));
output:
[?, a, b, , , ]
This will write a JTable to a tab separated file that can be easily imported into Excel. This works.
If you save an Excel worksheet as an XML document you could also build the XML file for EXCEL with code. I have done this with word so you do not have to use third-party packages.
This could code have the JTable taken out and then just write a tab separated to any text file and then import into Excel. I hope this helps.
Code:
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import javax.swing.JTable;
import javax.swing.table.TableModel;
public class excel {
String columnNames[] = { "Column 1", "Column 2", "Column 3" };
// Create some data
String dataValues[][] =
{
{ "12", "234", "67" },
{ "-123", "43", "853" },
{ "93", "89.2", "109" },
{ "279", "9033", "3092" }
};
JTable table;
excel() {
table = new JTable( dataValues, columnNames );
}
public void toExcel(JTable table, File file){
try{
TableModel model = table.getModel();
FileWriter excel = new FileWriter(file);
for(int i = 0; i < model.getColumnCount(); i++){
excel.write(model.getColumnName(i) + "\t");
}
excel.write("\n");
for(int i=0; i< model.getRowCount(); i++) {
for(int j=0; j < model.getColumnCount(); j++) {
excel.write(model.getValueAt(i,j).toString()+"\t");
}
excel.write("\n");
}
excel.close();
}catch(IOException e){ System.out.println(e); }
}
public static void main(String[] o) {
excel cv = new excel();
cv.toExcel(cv.table,new File("C:\\Users\\itpr13266\\Desktop\\cs.tbv"));
}
}
location ~ /issue([0-9]+) {
return 301 http://example.com/shop/issues/custom_isse_name$1;
}
Alternatively, in plain text: (also available as a a screenshot)
Bracket Matching -. .- Line Numbering
Smart Indent -. | | .- UML Editing / Viewing
Source Control Integration -. | | | | .- Code Folding
Error Markup -. | | | | | | .- Code Templates
Integrated Python Debugging -. | | | | | | | | .- Unit Testing
Multi-Language Support -. | | | | | | | | | | .- GUI Designer (Qt, Eric, etc)
Auto Code Completion -. | | | | | | | | | | | | .- Integrated DB Support
Commercial/Free -. | | | | | | | | | | | | | | .- Refactoring
Cross Platform -. | | | | | | | | | | | | | | | |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
Atom |Y |F |Y |Y*|Y |Y |Y |Y |Y |Y | |Y |Y | | | | |*many plugins
Editra |Y |F |Y |Y | | |Y |Y |Y |Y | |Y | | | | | |
Emacs |Y |F |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y | | | |
Eric Ide |Y |F |Y | |Y |Y | |Y | |Y | |Y | |Y | | | |
Geany |Y |F |Y*|Y | | | |Y |Y |Y | |Y | | | | | |*very limited
Gedit |Y |F |Y¹|Y | | | |Y |Y |Y | | |Y²| | | | |¹with plugin; ²sort of
Idle |Y |F |Y | |Y | | |Y |Y | | | | | | | | |
IntelliJ |Y |CF|Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |
JEdit |Y |F | |Y | | | | |Y |Y | |Y | | | | | |
KDevelop |Y |F |Y*|Y | | |Y |Y |Y |Y | |Y | | | | | |*no type inference
Komodo |Y |CF|Y |Y |Y |Y |Y |Y |Y |Y | |Y |Y |Y | |Y | |
NetBeans* |Y |F |Y |Y |Y | |Y |Y |Y |Y |Y |Y |Y |Y | | |Y |*pre-v7.0
Notepad++ |W |F |Y |Y | |Y*|Y*|Y*|Y |Y | |Y |Y*| | | | |*with plugin
Pfaide |W |C |Y |Y | | | |Y |Y |Y | |Y |Y | | | | |
PIDA |LW|F |Y |Y | | | |Y |Y |Y | |Y | | | | | |VIM based
PTVS |W |F |Y |Y |Y |Y |Y |Y |Y |Y | |Y | | |Y*| |Y |*WPF bsed
PyCharm |Y |CF|Y |Y*|Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |*JavaScript
PyDev (Eclipse) |Y |F |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y | | | |
PyScripter |W |F |Y | |Y |Y | |Y |Y |Y | |Y |Y |Y | | | |
PythonWin |W |F |Y | |Y | | |Y |Y | | |Y | | | | | |
SciTE |Y |F¹| |Y | |Y | |Y |Y |Y | |Y |Y | | | | |¹Mac version is
ScriptDev |W |C |Y |Y |Y |Y | |Y |Y |Y | |Y |Y | | | | | commercial
Spyder |Y |F |Y | |Y |Y | |Y |Y |Y | | | | | | | |
Sublime Text |Y |CF|Y |Y | |Y |Y |Y |Y |Y | |Y |Y |Y*| | | |extensible w/Python,
TextMate |M |F | |Y | | |Y |Y |Y |Y | |Y |Y | | | | | *PythonTestRunner
UliPad |Y |F |Y |Y |Y | | |Y |Y | | | |Y |Y | | | |
Vim |Y |F |Y |Y |Y |Y |Y |Y |Y |Y | |Y |Y |Y | | | |
Visual Studio |W |CF|Y |Y |Y |Y |Y |Y |Y |Y |? |Y |? |? |Y |? |Y |
Visual Studio Code|Y |F |Y |Y |Y |Y |Y |Y |Y |Y |? |Y |? |? |? |? |Y |uses plugins
WingIde |Y |C |Y |Y*|Y |Y |Y |Y |Y |Y | |Y |Y |Y | | | |*support for C
Zeus |W |C | | | | |Y |Y |Y |Y | |Y |Y | | | | |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
Cross Platform -' | | | | | | | | | | | | | | | |
Commercial/Free -' | | | | | | | | | | | | | | '- Refactoring
Auto Code Completion -' | | | | | | | | | | | | '- Integrated DB Support
Multi-Language Support -' | | | | | | | | | | '- GUI Designer (Qt, Eric, etc)
Integrated Python Debugging -' | | | | | | | | '- Unit Testing
Error Markup -' | | | | | | '- Code Templates
Source Control Integration -' | | | | '- Code Folding
Smart Indent -' | | '- UML Editing / Viewing
Bracket Matching -' '- Line Numbering
Acronyms used:
L - Linux
W - Windows
M - Mac
C - Commercial
F - Free
CF - Commercial with Free limited edition
? - To be confirmed
I don't mention basics like syntax highlighting as I expect these by default.
This is a just dry list reflecting your feedback and comments, I am not advocating any of these tools. I will keep updating this list as you keep posting your answers.
PS. Can you help me to add features of the above editors to the list (like auto-complete, debugging, etc.)?
We have a comprehensive wiki page for this question https://wiki.python.org/moin/IntegratedDevelopmentEnvironments
From the documentation:
It is necessary to keep in mind that the browsers do not know how to correctly show this error.
I suspect this is what's happening, if you inspect the HTTP to-and-fro using tools such as Firebug or Live HTTP Headers (both Firefox extensions) you'll be able to see what's really going on.
Go to Run and type "inetmgr", i.e IIS is opened and in the right corner Action window, select option change ".NET Framework version". Change it.
After that, reinstall your Visual studio 2010. It works on my computer, and that's why sharing.
If you want to know how many files and sub-directories exist from the present working directory you can use this one-liner
find . -maxdepth 1 -type d -print0 | xargs -0 -I {} sh -c 'echo -e $(find {} | wc -l) {}' | sort -n
This will work in GNU flavour, and just omit the -e from the echo command for BSD linux (e.g. OSX).
There are multiple ways which can solve the problem of extending a constructor function with a prototype in Javascript. Which of these methods is the 'best' solution is opinion based. However, here are two frequently used methods in order to extend a constructor's function prototype.
class Monster {_x000D_
constructor(health) {_x000D_
this.health = health_x000D_
}_x000D_
_x000D_
growl () {_x000D_
console.log("Grr!");_x000D_
}_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
class Monkey extends Monster {_x000D_
constructor (health) {_x000D_
super(health) // call super to execute the constructor function of Monster _x000D_
this.bananaCount = 5;_x000D_
}_x000D_
}_x000D_
_x000D_
const monkey = new Monkey(50);_x000D_
_x000D_
console.log(typeof Monster);_x000D_
console.log(monkey);
_x000D_
The above approach of using ES 2015
classes is nothing more than syntactic sugar over the prototypal inheritance pattern in javascript. Here the first log where we evaluate typeof Monster
we can observe that this is function. This is because classes are just constructor functions under the hood. Nonetheless you may like this way of implementing prototypal inheritance and definitively should learn it. It is used in major frameworks such as ReactJS
and Angular2+
.
Object.create()
:function makeMonkey (bananaCount) {_x000D_
_x000D_
// here we define the prototype_x000D_
const Monster = {_x000D_
health: 100,_x000D_
growl: function() {_x000D_
console.log("Grr!");}_x000D_
}_x000D_
_x000D_
const monkey = Object.create(Monster);_x000D_
monkey.bananaCount = bananaCount;_x000D_
_x000D_
return monkey;_x000D_
}_x000D_
_x000D_
_x000D_
const chimp = makeMonkey(30);_x000D_
_x000D_
chimp.growl();_x000D_
console.log(chimp.bananaCount);
_x000D_
This method uses the Object.create()
method which takes an object which will be the prototype of the newly created object it returns. Therefore we first create the prototype object in this function and then call Object.create()
which returns an empty object with the __proto__
property set to the Monster object. After this we can initialize all the properties of the object, in this example we assign the bananacount to the newly created object.
You need to implement your own MessageBodyReader
and MessageBodyWriter
for your class Lorg.shoppingsite.model.entity.jpa.User
.
package javax.ws.rs.ext;
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
public interface MessageBodyReader<T extends Object> {
public boolean isReadable(Class<?> type,
Type genericType,
Annotation[] annotations,
MediaType mediaType);
public T readFrom(Class<T> type,
Type genericType,
Annotation[] annotations,
MediaType mediaType,
MultivaluedMap<String, String> httpHeaders,
InputStream entityStream) throws IOException, WebApplicationException;
}
package javax.ws.rs.ext;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
public interface MessageBodyWriter<T extends Object> {
public boolean isWriteable(Class<?> type,
Type genericType,
Annotation[] annotations,
MediaType mediaType);
public long getSize(T t,
Class<?> type,
Type genericType,
Annotation[] annotations,
MediaType mediaType);
public void writeTo(T t,
Class<?> type,
Type genericType,
Annotation[] annotations,
MediaType mediaType,
MultivaluedMap<String, Object> httpHeaders,
OutputStream entityStream) throws IOException, WebApplicationException;
}
You cannot do it with just method, unless you use some javascript framework like jquery which supports it ..
string s = '<div id="myDiv"></div>'
var htmlObject = $(s); // jquery call
but still, it would not be found by the getElementById
because for that to work the element must be in the DOM... just creating in the memory does not insert it in the dom.
You would need to use append
or appendTo
or after
etc.. to put it in the dom first..
Of'course all these can be done through regular javascript but it would take more steps to accomplish the same thing... and the logic is the same in both cases..
Use a subquery:
SELECT * FROM
(
SELECT * FROM users ORDER BY rand() LIMIT 20
) T1
ORDER BY name
The inner query selects 20 users at random and the outer query orders the selected users by name.
SVN seems to handle binary deltas more efficiently than Git.
I had to decide on a versioning system for documentation (JPEG files, PDF files, and .odt files). I just tested adding a JPEG file and rotating it 90 degrees four times (to check effectiveness of binary deltas). Git's repository grew 400%. SVN's repository grew by only 11%.
So it looks like SVN is much more efficient with binary files.
So my choice is Git for source code and SVN for binary files like documentation.
There really seems no way for fooling the <a href= ..
into a POST method. However, given that you have access to CSS of a page, this can be substituted by using a form instead.
Unfortunately, the obvious way of just styling the button in CSS as an anchor tag, is not cross-browser compatible, since different browsers treat <button value= ...
differently.
Incorrect:
<form action='actbusy.php' method='post'>
<button type='submit' name='parameter' value='One'>Two</button>
</form>
The above example will be showing 'Two' and transmit 'parameter:One' in FireFox, while it will show 'One' and transmit also 'parameter:One' in IE8.
The way around is to use hidden input field(s) for delivering data and the button just for submitting it.
<form action='actbusy.php' method='post'>
<input class=hidden name='parameter' value='blaah'>
<button type='submit' name='delete' value='Delete'>Delete</button>
</form>
Note, that this method has a side effect that besides 'parameter:blaah' it will also deliver 'delete:Delete' as surplus parameters in POST.
You want to keep for a button the value attribute and button label between tags both the same ('Delete' on this case), since (as stated above) some browsers will display one and some display another as a button label.
I also had same error but with codeigniter application. I changed
my base URL in config.php to my localhost path
in htaccess I changed RewriteBase /"my folder name in htdocs"
and I able to login to my application.
Hope it might help.
An IDE which supports Android development is Processing for Android: http://wiki.processing.org/w/Android. Processing is its own language but it's easy to learn. Processing for Android requires the JDK and Android SDK to be installed but runs on its own. It runs on Linux, Mac OSX and Windows (on a side note: one can develop a desktop app in Processing and then compile it to target any of these operating systems). Its development is ongoing but it works. It's especially good for quickly sketching up an idea and running it on your Android phone (even if you plan to develop it further in another IDE).
There is an active support forum here: http://forum.processing.org/android-processing.
Or simply Use union, for simple array.
_.union([1,2,3,3], [3,5])
// [1,2,3,5]
The answer by @Darius is the most idiomatic (and probably more performant) method. One limitation is that the type you are checking has to be of type interface{}
. If you use a concrete type it will fail.
An alternative way to determine the type of something at run-time, including concrete types, is to use the Go reflect
package. Chaining TypeOf(x).Kind()
together you can get a reflect.Kind
value which is a uint
type: http://golang.org/pkg/reflect/#Kind
You can then do checks for types outside of a switch block, like so:
import (
"fmt"
"reflect"
)
// ....
x := 42
y := float32(43.3)
z := "hello"
xt := reflect.TypeOf(x).Kind()
yt := reflect.TypeOf(y).Kind()
zt := reflect.TypeOf(z).Kind()
fmt.Printf("%T: %s\n", xt, xt)
fmt.Printf("%T: %s\n", yt, yt)
fmt.Printf("%T: %s\n", zt, zt)
if xt == reflect.Int {
println(">> x is int")
}
if yt == reflect.Float32 {
println(">> y is float32")
}
if zt == reflect.String {
println(">> z is string")
}
Which prints outs:
reflect.Kind: int
reflect.Kind: float32
reflect.Kind: string
>> x is int
>> y is float32
>> z is string
Again, this is probably not the preferred way to do it, but it's good to know alternative options.
In the .Net standard 2.0:
string.IsNullOrEmpty()
: Indicates whether the specified string is null or an Empty string.
Console.WriteLine(string.IsNullOrEmpty(null)); // True
Console.WriteLine(string.IsNullOrEmpty("")); // True
Console.WriteLine(string.IsNullOrEmpty(" ")); // False
Console.WriteLine(string.IsNullOrEmpty(" ")); // False
string.IsNullOrWhiteSpace()
: Indicates whether a specified string is null, empty, or consists only of white-space characters.
Console.WriteLine(string.IsNullOrWhiteSpace(null)); // True
Console.WriteLine(string.IsNullOrWhiteSpace("")); // True
Console.WriteLine(string.IsNullOrWhiteSpace(" ")); // True
Console.WriteLine(string.IsNullOrWhiteSpace(" ")); // True
I had the *.pdb
files in the same folder and used the options from Arindam, but it still didn't work. Turns out I needed to enable Enable native code debugging which can be found under Project properties > Debug.
There are actually two ways in which strings can be made in javascript.
var str = 'Javascript';
This creates a primitive string value.
var obj = new String('Javascript');
This creates a wrapper object
of type String
.
typeof str // string
typeof obj // object
So the best way to check for equality is using the ===
operator because it checks value as well as type of both operands.
If you want to check for equality between two objects then using String.prototype.valueOf
is the correct way.
new String('javascript').valueOf() == new String('javascript').valueOf()
I'll try and answer several different things, however my contribution may not cover all of your questions. Maybe several of us can take different chunks out of this. However, this info should be helpful for you. Here we go..
Opening A Seperate File:
ChDir "[Path here]" 'get into the right folder here
Workbooks.Open Filename:= "[Path here]" 'include the filename in this path
'copy data into current workbook or whatever you want here
ActiveWindow.Close 'closes out the file
Opening A File With Specified Date If It Exists:
I'm not sure how to search your directory to see if a file exists, but in my case I wouldn't bother to search for it, I'd just try to open it and put in some error checking so that if it doesn't exist then display this message or do xyz.
Some common error checking statements:
On Error Resume Next 'if error occurs continues on to the next line (ignores it)
ChDir "[Path here]"
Workbooks.Open Filename:= "[Path here]" 'try to open file here
Or (better option):
if one doesn't exist then bring up either a message box or dialogue box to say "the file does not exist, would you like to create a new one?
you would most likely want to use the GoTo ErrorHandler
shown below to achieve this
On Error GoTo ErrorHandler:
ChDir "[Path here]"
Workbooks.Open Filename:= "[Path here]" 'try to open file here
ErrorHandler:
'Display error message or any code you want to run on error here
Much more info on Error handling here: http://www.cpearson.com/excel/errorhandling.htm
Also if you want to learn more or need to know more generally in VBA I would recommend Siddharth Rout's site, he has lots of tutorials and example code here: http://www.siddharthrout.com/vb-dot-net-and-excel/
Hope this helps!
Example on how to ensure error code doesn't run EVERYtime:
if you debug through the code without the Exit Sub
BEFORE the error handler you'll soon realize the error handler will be run everytime regarldess of if there is an error or not. The link below the code example shows a previous answer to this question.
Sub Macro
On Error GoTo ErrorHandler:
ChDir "[Path here]"
Workbooks.Open Filename:= "[Path here]" 'try to open file here
Exit Sub 'Code will exit BEFORE ErrorHandler if everything goes smoothly
'Otherwise, on error, ErrorHandler will be run
ErrorHandler:
'Display error message or any code you want to run on error here
End Sub
Also, look at this other question in you need more reference to how this works: goto block not working VBA
Listen to window:scroll
event for window/document level scrolling and element's scroll
event for element level scrolling.
@HostListener('window:scroll', ['$event'])
onWindowScroll($event) {
}
or
<div (window:scroll)="onWindowScroll($event)">
@HostListener('scroll', ['$event'])
onElementScroll($event) {
}
or
<div (scroll)="onElementScroll($event)">
@HostListener('scroll', ['$event'])
won't work if the host element itself is not scroll-able.
Useful sns.heatmap
api is here. Check out the parameters, there are a good number of them. Example:
import seaborn as sns
%matplotlib inline
idx= ['aaa','bbb','ccc','ddd','eee']
cols = list('ABCD')
df = DataFrame(abs(np.random.randn(5,4)), index=idx, columns=cols)
# _r reverses the normal order of the color map 'RdYlGn'
sns.heatmap(df, cmap='RdYlGn_r', linewidths=0.5, annot=True)
For elementwise multiplication of matrix
objects, you can use numpy.multiply
:
import numpy as np
a = np.array([[1,2],[3,4]])
b = np.array([[5,6],[7,8]])
np.multiply(a,b)
Result
array([[ 5, 12],
[21, 32]])
However, you should really use array
instead of matrix
. matrix
objects have all sorts of horrible incompatibilities with regular ndarrays. With ndarrays, you can just use *
for elementwise multiplication:
a * b
If you're on Python 3.5+, you don't even lose the ability to perform matrix multiplication with an operator, because @
does matrix multiplication now:
a @ b # matrix multiplication
Along with @PaulStock's answer, Depending on your connection type, your variable names and SQLStatement/SQLStatementSource Changes
https://docs.microsoft.com/en-us/sql/integration-services/control-flow/execute-sql-task
The main differences between InnoDB and MyISAM ("with respect to designing a table or database" you asked about) are support for "referential integrity" and "transactions".
If you need the database to enforce foreign key constraints, or you need the database to support transactions (i.e. changes made by two or more DML operations handled as single unit of work, with all of the changes either applied, or all the changes reverted) then you would choose the InnoDB engine, since these features are absent from the MyISAM engine.
Those are the two biggest differences. Another big difference is concurrency. With MyISAM, a DML statement will obtain an exclusive lock on the table, and while that lock is held, no other session can perform a SELECT or a DML operation on the table.
Those two specific engines you asked about (InnoDB and MyISAM) have different design goals. MySQL also has other storage engines, with their own design goals.
So, in choosing between InnoDB and MyISAM, the first step is in determining if you need the features provided by InnoDB. If not, then MyISAM is up for consideration.
A more detailed discussion of differences is rather impractical (in this forum) absent a more detailed discussion of the problem space... how the application will use the database, how many tables, size of the tables, the transaction load, volumes of select, insert, updates, concurrency requirements, replication features, etc.
The logical design of the database should be centered around data analysis and user requirements; the choice to use a relational database would come later, and even later would the choice of MySQL as a relational database management system, and then the selection of a storage engine for each table.
Yes.
try {
Somecode();
catch (Exception $e) {
// handle or ignore exception here.
}
however note that php also has error codes separate from exceptions, a legacy holdover from before php had oop primitives. Most library builtins still raise error codes, not exceptions. To ignore an error code call the function prefixed with @:
@myfunction();
This query works on Microsoft SQL Server.
select distinct format( cast('2010-01-01' as datetime) + ( a.v / 10 ), 'yyyy-MM-dd' ) as aDate
from (
SELECT ones.n + 10 * tens.n + 100 * hundreds.n + 1000 * thousands.n as v
FROM (VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) ones(n),
(VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) tens(n),
(VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) hundreds(n),
(VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) thousands(n)
) a
where format( cast('2010-01-01' as datetime) + ( a.v / 10 ), 'yyyy-MM-dd' ) < cast('2010-01-13' as datetime)
order by aDate asc;
Now let's look at how it works.
The inner query merely returns a list of integers from 0 to 9999. It will give us a range of 10,000 values for calculating dates. You can get more dates by adding rows for ten_thousands and hundred_thousands and so forth.
SELECT ones.n + 10 * tens.n + 100 * hundreds.n + 1000 * thousands.n as v
FROM (VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) ones(n),
(VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) tens(n),
(VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) hundreds(n),
(VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) thousands(n)
) a;
This part converts the string to a date and adds a number to it from the inner query.
cast('2010-01-01' as datetime) + ( a.v / 10 )
Then we convert the result into the format you want. This is also the column name!
format( cast('2010-01-01' as datetime) + ( a.v / 10 ), 'yyyy-MM-dd' )
Next we extract only the distinct values and give the column name an alias of aDate.
distinct format( cast('2010-01-01' as datetime) + ( a.v / 10 ), 'yyyy-MM-dd' ) as aDate
We use the where clause to filter in only dates within the range you want. Notice that we use the column name here since SQL Server does not accept the column alias, aDate, within the where clause.
where format( cast('2010-01-01' as datetime) + ( a.v / 10 ), 'yyyy-MM-dd' ) < cast('2010-01-13' as datetime)
Lastly, we sort the results.
order by aDate asc;
To answer your direct question, it is:
Range("A1").NumberFormat = "@"
Or
Cells(1,1).NumberFormat = "@"
However, I suggest making changing the format to what you actually want displayed. This allows you to retain the data type in the cell and easily use cell formulas to manipulate the data.
When using HTTPS instead of ON the binding, put it IN the binding with the httpsTransport
tag:
<binding name="MyServiceBinding">
<security defaultAlgorithmSuite="Basic256Rsa15"
authenticationMode="MutualCertificate" requireDerivedKeys="true"
securityHeaderLayout="Lax" includeTimestamp="true"
messageProtectionOrder="SignBeforeEncrypt"
messageSecurityVersion="WSSecurity10WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10"
requireSignatureConfirmation="false">
<localClientSettings detectReplays="true" />
<localServiceSettings detectReplays="true" />
<secureConversationBootstrap keyEntropyMode="CombinedEntropy" />
</security>
<textMessageEncoding messageVersion="Soap11WSAddressing10">
<readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647"
maxArrayLength="2147483647" maxBytesPerRead="4096"
maxNameTableCharCount="16384"/>
</textMessageEncoding>
<httpsTransport maxReceivedMessageSize="2147483647"
maxBufferSize="2147483647" maxBufferPoolSize="2147483647"
requireClientCertificate="false" />
</binding>
You need to go here https://security.google.com/settings/security/apppasswords
then select Gmail and then select device. then click on Generate. Simply Copy & Paste password which is generated by Google.
I've recently found even more interesting way to create any ValueNode
or ContainerNode
(Jackson v2.3).
ObjectNode node = JsonNodeFactory.instance.objectNode();
JavaScript:
document.getElementsByTagName('head')[0].appendChild( ... );
Make DOM element like so:
link=document.createElement('link');
link.href='href';
link.rel='rel';
document.getElementsByTagName('head')[0].appendChild(link);
You can use from root directory:
RewriteEngine On
RewriteRule ^(?:system)\b.* /403.html
Or:
RewriteRule ^(?:system)\b.* /403.php # with header('HTTP/1.0 403 Forbidden');
Right-click the project, select Properties then under 'Configuration properties | Linker | Input | Ignore specific Library and write msvcrtd.lib
Yes, it's
use Illuminate\Support\Facades\Redirect;
return Redirect::to('http://heera.it');
Update: Redirect::away('url')
(For external link, Laravel Version 4.19):
public function away($path, $status = 302, $headers = array())
{
return $this->createRedirect($path, $status, $headers);
}
An update to munsellj's update..
I got this working in development just by adding localhost:3000 to the 'Website URL' option and leaving the App Domains box blank. As munsellj mentioned, make sure you've added a website platform.
It means if the screen size is 1024 then only apply below CSS rules.
An assertion allows for detecting defects in the code. You can turn on assertions for testing and debugging while leaving them off when your program is in production.
Why assert something when you know it is true? It is only true when everything is working properly. If the program has a defect, it might not actually be true. Detecting this earlier in the process lets you know something is wrong.
An assert
statement contains this statement along with an optional String
message.
The syntax for an assert statement has two forms:
assert boolean_expression;
assert boolean_expression: error_message;
Here are some basic rules which govern where assertions should be used and where they should not be used. Assertions should be used for:
Validating input parameters of a private method. NOT for public methods. public
methods should throw regular exceptions when passed bad parameters.
Anywhere in the program to ensure the validity of a fact which is almost certainly true.
For example, if you are sure that it will only be either 1 or 2, you can use an assertion like this:
...
if (i == 1) {
...
}
else if (i == 2) {
...
} else {
assert false : "cannot happen. i is " + i;
}
...
Assertions should not be used for:
Validating input parameters of a public method. Since assertions may not always be executed, the regular exception mechanism should be used.
Validating constraints on something that is input by the user. Same as above.
Should not be used for side effects.
For example this is not a proper use because here the assertion is used for its side effect of calling of the doSomething()
method.
public boolean doSomething() {
...
}
public void someMethod() {
assert doSomething();
}
The only case where this could be justified is when you are trying to find out whether or not assertions are enabled in your code:
boolean enabled = false;
assert enabled = true;
if (enabled) {
System.out.println("Assertions are enabled");
} else {
System.out.println("Assertions are disabled");
}
Try this:
alert("Successful Message");
location.reload();
You can look in sys.types or use TYPE_ID:
IF TYPE_ID(N'MyType') IS NULL ...
Just a precaution: using type_id won't verify that the type is a table type--just that a type by that name exists. Otherwise gbn's query is probably better.
The first allocates an object with automatic storage duration, which means it will be destructed automatically upon exit from the scope in which it is defined.
The second allocated an object with dynamic storage duration, which means it will not be destructed until you explicitly use delete
to do so.
The other queries are all going base on any ONE of the conditions qualifying and it will return a record... if you want to make sure the BOTH columns of table A are matched, you'll have to do something like...
select
tA.Col1,
tA.Col2,
tB.Val
from
TableA tA
join TableB tB
on ( tA.Col1 = tB.Col1 OR tA.Col1 = tB.Col2 )
AND ( tA.Col2 = tB.Col1 OR tA.Col2 = tB.Col2 )
The problem is the std namespace you are missing. cout
is in the std namespace.
Add using namespace std;
after the #include
All valid characters that can be used in a URI (a URL is a type of URI) are defined in RFC 3986.
All other characters can be used in a URL provided that they are "URL Encoded" first. This involves changing the invalid character for specific "codes" (usually in the form of the percent symbol (%) followed by a hexadecimal number).
This link, HTML URL Encoding Reference, contains a list of the encodings for invalid characters.
let JSONData = jsonString.data(using: .utf8)!
let jsonResult = try JSONSerialization.jsonObject(with: data, options: .mutableLeaves)
guard let userDictionary = jsonResult as? Dictionary<String, AnyObject> else {
throw NSError()}
Tested code, initially creates a single archive file, then splits it:
gzip -c file.orig > file.gz
CHUNKSIZE=1073741824
PARTCNT=$[$(stat -c%s file.gz) / $CHUNKSIZE]
# the remainder is taken care of, for example for
# 1 GiB + 1 bytes PARTCNT is 1 and seq 0 $PARTCNT covers
# all of file
for n in `seq 0 $PARTCNT`
do
dd if=file.gz of=part.$n bs=$CHUNKSIZE skip=$n count=1
done
This variant omits creating a single archive file and goes straight to creating parts:
gzip -c file.orig |
( CHUNKSIZE=1073741824;
i=0;
while true; do
i=$[i+1];
head -c "$CHUNKSIZE" > "part.$i";
[ "$CHUNKSIZE" -eq $(stat -c%s "part.$i") ] || break;
done; )
In this variant, if the archive's file size is divisible by $CHUNKSIZE
, then the last partial file will have file size 0 bytes.
Reader they show at http://www.webqr.com/index.html works like a charm, but literaly, you need the one on the webpage, the github version it's really hard to make it work, however, it is possible. The best way to go is reverse-engineer the example shown at the webpage.
However, to edit and get the full potential out of it, it's not so easy. At some point I may post the stripped-down reverse-engineered QR reader, but in the meantime have some fun hacking the code.
Happy coding.
in Nodejs you can use Buffer :
let str = "hello world"
let buffer = Buffer.alloc(2, str) // replace 2 by 1 for the first char
console.log(buffer.toString('utf-8')) // display he
console.log(buffer.toString('utf-8').length) // display 2
when using String array, you have to give size of array while initializing
eg
String[] str = new String[10];
you can use index 0-9 to store values
str[0] = "value1"
str[1] = "value2"
str[2] = "value3"
str[3] = "value4"
str[4] = "value5"
str[5] = "value6"
str[6] = "value7"
str[7] = "value8"
str[8] = "value9"
str[9] = "value10"
if you are using ArrayList instread of string array, you can use it without initializing size of array ArrayList str = new ArrayList();
you can add value by using add method of Arraylist
str.add("Value1");
get retrieve a value from arraylist, you can use get method
String s = str.get(0);
find total number of items by size method
int nCount = str.size();
read more from here
If you're simply trying to scroll to the specified element, you can use the scrollIntoView method of the Element. Here's an example :
$target.get(0).scrollIntoView();
You can try using command : install.packages('*package_name', dependencies = TRUE)
For example is you have to install 'caret' package in your R machine in linux : install.packages('caret', dependencies = TRUE)
Doing so, all the dependencies for the package will also be downloaded.
color
and fill
are separate aesthetics. Since you want to modify the color you need to use the corresponding scale:
d + scale_color_manual(values=c("#CC6666", "#9999CC"))
is what you want.
There is a similar problem.it is a tomcat digital signature.
$ gpg --verify apache-tomcat-9.0.16-windows-x64.zip.asc apache-tomcat-9.0.16-windows-
x64.zip
gpg: Signature made 2019?02? 5? 0:32:50
gpg: using RSA key A9C5DF4D22E99998D9875A5110C01C5A2F6059E7
gpg: Can't check signature: No public key
but then I use the RSA key it provided to receive the public key to verify.
$ gpg --receive-keys A9C5DF4D22E99998D9875A5110C01C5A2F6059E7
gpg: key 10C01C5A2F6059E7: 38 signatures not checked due to missing keys
gpg: key 10C01C5A2F6059E7: public key "Mark E D Thomas <[email protected]>" imported
gpg: no ultimately trusted keys found
gpg: Total number processed: 1
gpg: imported: 1
Then successfully.
$ gpg --verify apache-tomcat-9.0.16-windows-x64.zip.asc
gpg: assuming signed data in 'apache-tomcat-9.0.16-windows-x64.zip'
gpg: Signature made 2019?02? 5? 0:32:50
gpg: using RSA key A9C5DF4D22E99998D9875A5110C01C5A2F6059E7
gpg: Good signature from "Mark E D Thomas <[email protected]>" [unknown]
gpg: WARNING: This key is not certified with a trusted signature!
gpg: There is no indication that the signature belongs to the owner.
Primary key fingerprint: A9C5 DF4D 22E9 9998 D987 5A51 10C0 1C5A 2F60 59E7
Swift Version :
// Attributed String for Label
let plainText = "Apkia"
let styledText = NSMutableAttributedString(string: plainText)
// Set Attribuets for Color, HyperLink and Font Size
let attributes = [NSFontAttributeName: UIFont.systemFontOfSize(14.0), NSLinkAttributeName:NSURL(string: "http://apkia.com/")!, NSForegroundColorAttributeName: UIColor.blueColor()]
styledText.setAttributes(attributes, range: NSMakeRange(0, plainText.characters.count))
registerLabel.attributedText = styledText
Like this:
string str= test[0]+test[1];
You can also use a loop:
for(int i=0; i<2; i++)
str += test[i];
Inside file strings.xml
define a String resource like this:
<string name="string_to_format">Amount: %1$f for %2$d days%3$s</string>
Inside your code (assume it inherits from Context) simply do the following:
String formattedString = getString(R.string.string_to_format, floatVar, decimalVar, stringVar);
(In comparison to the answer from LocalPCGuy or Giovanny Farto M. the String.format method is not needed.)
try this :
sudo apt-get install libblas-dev libatlas-base-dev
I had a similar issue on Ubuntu 14.04. For me the following Ubuntu packages
That's a very complex question for a simple answer.
You may want to take a look at existing API frameworks, like Swagger Specification (OpenAPI), and services like apiary.io and apiblueprint.org.
Also, here's an example of the same REST API described, organized and even styled in three different ways. It may be a good start for you to learn from existing common ways.
At the very top level I think quality REST API docs require at least the following:
Also there are a lot of JSON/XML-based doc frameworks which can parse your API definition or schema and generate a convenient set of docs for you. But the choice for a doc generation system depends on your project, language, development environment and many other things.
client.py
import socket
s = socket.socket()
s.connect(('127.0.0.1',12345))
while True:
str = raw_input("S: ")
s.send(str.encode());
if(str == "Bye" or str == "bye"):
break
print "N:",s.recv(1024).decode()
s.close()
server.py
import socket
s = socket.socket()
port = 12345
s.bind(('', port))
s.listen(5)
c, addr = s.accept()
print "Socket Up and running with a connection from",addr
while True:
rcvdData = c.recv(1024).decode()
print "S:",rcvdData
sendData = raw_input("N: ")
c.send(sendData.encode())
if(sendData == "Bye" or sendData == "bye"):
break
c.close()
This should be the code for a small prototype for the chatting app you wanted. Run both of them in separate terminals but then just check for the ports.
I had the same need in my app (with complex nested components structure) and I unfortunately did not succeed to make it work.
Finally I used vue-scrollto that works fine !
From: http://www.csharp-examples.net/string-format-datetime/
string.Format("{0:t tt}", datetime); // -> "P PM" or "A AM"
To: Killercam Thanks for your solutions. I tried the first solution for an hour, but didn't work for me.
I used scripts generate method to move data from SQL Server 2012 to SQL Server 2008 R2 as steps bellow:
In the 2012 SQL Management Studio
It works for me.
There is a web-based project for this that is relatively early on called Pongo. It requires installing Python and some dependencies, but it should run on Windows.
If you are trying to return the time like a stopwatch you could use the following API which returns the time in milliseconds since system startup:
Public Declare Function GetTickCount Lib "kernel32.dll" () As Long
Sub testTimer()
Dim t As Long
t = GetTickCount
For i = 1 To 1000000
a = a + 1
Next
MsgBox GetTickCount - t, , "Milliseconds"
End Sub
after http://www.pcreview.co.uk/forums/grab-time-milliseconds-included-vba-t994765.html (as timeGetTime in winmm.dll was not working for me and QueryPerformanceCounter was too complicated for the task needed)
Following is an ES6 example of how you can access the property of an object using a property name that has been dynamically generated by concatenating two strings.
var suffix = " name";
var person = {
["first" + suffix]: "Nicholas",
["last" + suffix]: "Zakas"
};
console.log(person["first name"]); // "Nicholas"
console.log(person["last name"]); // "Zakas"
This is called computed property names
Maybe try putting it all in the end if and use a else to skip the code this will make it so that you are able not use the GoTo.
If 6 - ((Int_height(Int_Column - 1) - 1) + Int_direction(e, 1)) = 7 Or (Int_Column - 1) + Int_direction(e, 0) = -1 Or (Int_Column - 1) + Int_direction(e, 0) = 7 Then
Else
If Grid((Int_Column - 1) + Int_direction(e, 0), 6 - ((Int_height(Int_Column - 1) - 1) + Int_direction(e, 1))) = "_" Then
Console.ReadLine()
End If
End If
If it is not a typo, as pointed out earlier, it could be wrong compiler options like compiling 64 bit under 32 bit. It must not be a toolchain.
In my testing all IMPL classes had the field "pid". This has worked for me:
public static int getPid(Process process) {
try {
Class<?> cProcessImpl = process.getClass();
Field fPid = cProcessImpl.getDeclaredField("pid");
if (!fPid.isAccessible()) {
fPid.setAccessible(true);
}
return fPid.getInt(process);
} catch (Exception e) {
return -1;
}
}
Just make sure the returned value is not -1. If it is, then parse the output of ps
.
Just wanted to make a time comparison for both solutions (for 30K rows DF):
In [1]: df = DataFrame({'foo':['a','b','c'], 'bar':[1, 2, 3], 'new':['apple', 'banana', 'pear']})
In [2]: big = pd.concat([df] * 10**4, ignore_index=True)
In [3]: big.shape
Out[3]: (30000, 3)
In [4]: %timeit big.apply(lambda x:'%s_%s_%s' % (x['bar'],x['foo'],x['new']),axis=1)
1 loop, best of 3: 881 ms per loop
In [5]: %timeit big['bar'].astype(str)+'_'+big['foo']+'_'+big['new']
10 loops, best of 3: 44.2 ms per loop
a few more options:
In [6]: %timeit big.ix[:, :-1].astype(str).add('_').sum(axis=1).str.cat(big.new)
10 loops, best of 3: 72.2 ms per loop
In [11]: %timeit big.astype(str).add('_').sum(axis=1).str[:-1]
10 loops, best of 3: 82.3 ms per loop
I had the same problem, but non of the asweres worked for me. I am using bootstap and the following css code helped me:
label {
display: contents!important;
}
Some of these above answers didn't work for me but this did. Just in case someone else has the same issue.
ng-show="column != 'vendorid' && column !='billingMonth'"
This link has some useful suggestions: http://forums.iis.net/t/1085990.aspx
It depends on where you have the config settings stored. By default IIS7 will have all of it's configuration settings stored in a file called "ApplicationHost.Config". If you have delegation configured then you will see site/app related config settings getting written to web.config file for the site/app. With IIS7 on vista there is an automatica backup file for master configuration is created. This file is called "application.config.backup" and it resides inside "C:\Windows\System32\inetsrv\config" You could rename this file to applicationHost.config and replace it with the applicationHost.config inside the config folder. IIS7 on server release will have better configuration back up story, but for now I recommend using APPCMD to backup/restore your configuration on regualr basis. Example: APPCMD ADD BACK "MYBACKUP" Another option (really the last option) is to uninstall/reinstall IIS along with WPAS (Windows Process activation service).
You can also use std::vectors
for achieving this:
using std::vector< std::vector<int> >
Example:
std::vector< std::vector<int> > a;
//m * n is the size of the matrix
int m = 2, n = 4;
//Grow rows by m
a.resize(m);
for(int i = 0 ; i < m ; ++i)
{
//Grow Columns by n
a[i].resize(n);
}
//Now you have matrix m*n with default values
//you can use the Matrix, now
a[1][0]=1;
a[1][1]=2;
a[1][2]=3;
a[1][3]=4;
//OR
for(i = 0 ; i < m ; ++i)
{
for(int j = 0 ; j < n ; ++j)
{ //modify matrix
int x = a[i][j];
}
}
It is obvious but still it was hard to figure out for me,
Please check if your mobile device has enough space to install the apk. and it is not full.
The root.after(ms, func) is the method you need to use. Just call it once before the mainloop starts and reschedule it inside the bound function every time it is called. Here is an example:
from tkinter import *
import time
def update_clock():
timer_label.config(text=time.strftime('%H:%M:%S',time.localtime()),
font='Times 25') # change the text of the time_label according to the current time
root.after(100, update_clock) # reschedule update_clock function to update time_label every 100 ms
root = Tk() # create the root window
timer_label = Label(root, justify='center') # create the label for timer
timer_label.pack() # show the timer_label using pack geometry manager
root.after(0, update_clock) # schedule update_clock function first call
root.mainloop() # start the root window mainloop
The following worked for me (based on example for a Django model, but you can pretty much use the code of the delete
method on its own).
import boto3
from boto3.session import Session
from django.conf import settings
class Video(models.Model):
title=models.CharField(max_length=500)
description=models.TextField(default="")
creation_date=models.DateTimeField(default=timezone.now)
videofile=models.FileField(upload_to='videos/', null=True, verbose_name="")
tags = TaggableManager()
actions = ['delete']
def __str__(self):
return self.title + ": " + str(self.videofile)
def delete(self, *args, **kwargs):
session = Session (settings.AWS_ACCESS_KEY_ID, settings.AWS_SECRET_ACCESS_KEY)
s3_resource = session.resource('s3')
s3_bucket = s3_resource.Bucket(settings.AWS_STORAGE_BUCKET_NAME)
file_path = "media/" + str(self.videofile)
response = s3_bucket.delete_objects(
Delete={
'Objects': [
{
'Key': file_path
}
]
})
super(Video, self).delete(*args, **kwargs)
I think you have multiple adb server running, genymotion could be one of them, but also Xamarin - Visual studio for mac OS could be running an adb server, closing Visual studio worked for me
The includes
(formerly called contains
and include
) method compares objects by reference (or more precisely, with ===
). Because the two object literals of {"b": 2}
in your example represent different instances, they are not equal. Notice:
({"b": 2} === {"b": 2})
> false
However, this will work because there is only one instance of {"b": 2}
:
var a = {"a": 1}, b = {"b": 2};
_.includes([a, b], b);
> true
On the other hand, the where
(deprecated in v4) and find
methods compare objects by their properties, so they don't require reference equality. As an alternative to includes
, you might want to try some
(also aliased as any
):
_.some([{"a": 1}, {"b": 2}], {"b": 2})
> true
I found a way to do it (dont know if it is the best but it works)
string oldFile = "oldFile.pdf";
string newFile = "newFile.pdf";
// open the reader
PdfReader reader = new PdfReader(oldFile);
Rectangle size = reader.GetPageSizeWithRotation(1);
Document document = new Document(size);
// open the writer
FileStream fs = new FileStream(newFile, FileMode.Create, FileAccess.Write);
PdfWriter writer = PdfWriter.GetInstance(document, fs);
document.Open();
// the pdf content
PdfContentByte cb = writer.DirectContent;
// select the font properties
BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252,BaseFont.NOT_EMBEDDED);
cb.SetColorFill(BaseColor.DARK_GRAY);
cb.SetFontAndSize(bf, 8);
// write the text in the pdf content
cb.BeginText();
string text = "Some random blablablabla...";
// put the alignment and coordinates here
cb.ShowTextAligned(1, text, 520, 640, 0);
cb.EndText();
cb.BeginText();
text = "Other random blabla...";
// put the alignment and coordinates here
cb.ShowTextAligned(2, text, 100, 200, 0);
cb.EndText();
// create the new page and add it to the pdf
PdfImportedPage page = writer.GetImportedPage(reader, 1);
cb.AddTemplate(page, 0, 0);
// close the streams and voilá the file should be changed :)
document.Close();
fs.Close();
writer.Close();
reader.Close();
I hope this can be usefull for someone =) (and post here any errors)
Had same problem - it was somewhere in the ca certificate, so I used the ca bundle used for curl, and it worked. You can download the curl ca bundle here: https://curl.haxx.se/docs/caextract.html
For encryption and security issues see this helpful article:
https://www.venditan.com/labs/2014/06/26/ssl-and-php-streams-part-1-you-are-doing-it-wrongtm/432
Here is the example:
$url = 'https://www.example.com/api/list';
$cn_match = 'www.example.com';
$data = array (
'apikey' => '[example api key here]',
'limit' => intval($limit),
'offset' => intval($offset)
);
// use key 'http' even if you send the request to https://...
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data)
)
, 'ssl' => array(
'verify_peer' => true,
'cafile' => [path to file] . "cacert.pem",
'ciphers' => 'HIGH:TLSv1.2:TLSv1.1:TLSv1.0:!SSLv3:!SSLv2',
'CN_match' => $cn_match,
'disable_compression' => true,
)
);
$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);
Hope that helps
You want to use css float for this, you can put it directly in your code.
<body>
<img src="website_art.png" height= "75" width="235" style="float:left;"/>
<h3 style="float:right;">The Art of Gaming</h3>
</body>
But I would really suggest learning the basics of css and splitting all your styling out to a separate style sheet, and use classes. It will help you in the future. A good place to start is w3schools or, perhaps later down the path, Mozzila Dev. Network (MDN).
HTML:
<body>
<img src="website_art.png" class="myImage"/>
<h3 class="heading">The Art of Gaming</h3>
</body>
CSS:
.myImage {
float: left;
height: 75px;
width: 235px;
font-family: Veranda;
}
.heading {
float:right;
}
You can do this via the information_schema tables. For example:
SELECT
tc.table_schema,
tc.constraint_name,
tc.table_name,
kcu.column_name,
ccu.table_schema AS foreign_table_schema,
ccu.table_name AS foreign_table_name,
ccu.column_name AS foreign_column_name
FROM
information_schema.table_constraints AS tc
JOIN information_schema.key_column_usage AS kcu
ON tc.constraint_name = kcu.constraint_name
AND tc.table_schema = kcu.table_schema
JOIN information_schema.constraint_column_usage AS ccu
ON ccu.constraint_name = tc.constraint_name
AND ccu.table_schema = tc.table_schema
WHERE tc.constraint_type = 'FOREIGN KEY' AND tc.table_name='mytable';
You can use apply
for this, and it's a bit neater:
import numpy as np
import pandas as pd
np.random.seed(1)
df = pd.DataFrame(np.random.randn(4,4)* 4 + 3)
0 1 2 3
0 9.497381 0.552974 0.887313 -1.291874
1 6.461631 -6.206155 9.979247 -0.044828
2 4.276156 2.002518 8.848432 -5.240563
3 1.710331 1.463783 7.535078 -1.399565
df.apply(lambda x: (x - np.mean(x)) / (np.max(x) - np.min(x)))
0 1 2 3
0 0.515087 0.133967 -0.651699 0.135175
1 0.125241 -0.689446 0.348301 0.375188
2 -0.155414 0.310554 0.223925 -0.624812
3 -0.484913 0.244924 0.079473 0.114448
Also, it works nicely with groupby
, if you select the relevant columns:
df['grp'] = ['A', 'A', 'B', 'B']
0 1 2 3 grp
0 9.497381 0.552974 0.887313 -1.291874 A
1 6.461631 -6.206155 9.979247 -0.044828 A
2 4.276156 2.002518 8.848432 -5.240563 B
3 1.710331 1.463783 7.535078 -1.399565 B
df.groupby(['grp'])[[0,1,2,3]].apply(lambda x: (x - np.mean(x)) / (np.max(x) - np.min(x)))
0 1 2 3
0 0.5 0.5 -0.5 -0.5
1 -0.5 -0.5 0.5 0.5
2 0.5 0.5 0.5 -0.5
3 -0.5 -0.5 -0.5 0.5
I have a simpler solution for you:
window.onload = window.onresize = (event) => {
//Your Code Here
}
I've tested this an it works great, on the plus side it's compact and uncomplicated like the other examples here.
I had a similar issue but I had to consider other issues that @apaul34208 example did not tackle. In my case;
Not the most elegant of examples but it does the trick for me. Consider using throttling the window resize (https://lodash.com/)
var TextFit = function(){_x000D_
var container = $('.container');_x000D_
container.each(function(){_x000D_
var container_width = $(this).width(),_x000D_
width_offset = parseInt($(this).data('width-offset')),_x000D_
font_container = $(this).find('.font-container');_x000D_
_x000D_
if ( width_offset > 0 ) {_x000D_
container_width -= width_offset;_x000D_
}_x000D_
_x000D_
font_container.each(function(){_x000D_
var font_container_width = $(this).width(),_x000D_
font_size = parseFloat( $(this).css('font-size') );_x000D_
_x000D_
var diff = Math.max(container_width, font_container_width) - Math.min(container_width, font_container_width);_x000D_
_x000D_
var diff_percentage = Math.round( ( diff / Math.max(container_width, font_container_width) ) * 100 );_x000D_
_x000D_
if (diff_percentage !== 0){_x000D_
if ( container_width > font_container_width ) {_x000D_
new_font_size = font_size + Math.round( ( font_size / 100 ) * diff_percentage );_x000D_
} else if ( container_width < font_container_width ) {_x000D_
new_font_size = font_size - Math.round( ( font_size / 100 ) * diff_percentage );_x000D_
}_x000D_
}_x000D_
$(this).css('font-size', new_font_size + 'px');_x000D_
});_x000D_
});_x000D_
}_x000D_
_x000D_
$(function(){_x000D_
TextFit();_x000D_
$(window).resize(function(){_x000D_
TextFit();_x000D_
});_x000D_
});
_x000D_
.container {_x000D_
width:341px;_x000D_
height:341px;_x000D_
background-color:#000;_x000D_
padding:20px;_x000D_
}_x000D_
.font-container {_x000D_
font-size:131px;_x000D_
text-align:center;_x000D_
color:#fff;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
_x000D_
<div class="container" data-width-offset="10">_x000D_
<span class="font-container">£5000</span>_x000D_
</div>
_x000D_
This worked for me.
Single-clicking a row triggers the code-behind.
XAML:
<ListView x:Name="MyListView" MouseLeftButtonUp="MyListView_MouseLeftButtonUp">
<GridView>
<!-- Declare GridViewColumns. -->
</GridView>
</ListView.View>
Code-behind:
private void MyListView_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
System.Windows.Controls.ListView list = (System.Windows.Controls.ListView)sender;
MyClass selectedObject = (MyClass)list.SelectedItem;
// Do stuff with the selectedObject.
}
This is a slight variation, but PJW's solution didn't quite work for me:
java -version 2>&1 | head -n 1 | cut -d'"' -f2
just cut the string on the delimiter "
(double quotes) and get the second field.
In my case I used blow code for different environment.
document.cookie = name +`=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;Domain=.${document.domain.split('.').splice(1).join('.')}`;
Once you get what abstract means in Java, you would ask: why they put this in ? Java may work without abstract stuff, BUT it makes part of a certain OO style or vocabulary. There exists really situations where an abstract class or method is an elegant way to express the program authors intention. Most when you are programming a framework or a library that will be used by others.
class Materials:
Shaded, Shiny, Transparent, Matte = range(4)
>>> print Materials.Matte
3
Get Current class name of Asp.net
string CurrentClass = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name.ToString();
For some commands, such as mtr + (plus) and - (minus) work to scroll up and down.
var object = { "a": 1, "b": 2};_x000D_
$.each(object, function(key, value){_x000D_
console.log(key + ": " + object[key]);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
_x000D_
//output
a: 1
b: 2
http://msdn.microsoft.com/en-us/library/83fhsxwc.aspx
Remember that using uninitialized variables in C# is not allowed.
With
bool foo = new bool();
foo will have the default value.
Boolean default is false
I noticed that the emulator defaults to only Core 0, where most Windows applications will default to "any" core. Also, if you put it on another core (like the last core), it may make the emulator go crazy. If you can, you can try putting your heavy-CPU usage applications on the other CPU cores for a boost in speed.
Hardware-wise, get the fastest CPU you can get that works for single-core applications. More than 2 cores might not experience a huge difference in terms of emulator performance.
Eclipse + the Android emulator together eat up a ton of RAM. I would recommend 3 gigs of RAM at least because I used a system with 2 gigs of RAM, and it slowed down because the system ran out of RAM and started to use the page file.
I feel that the best CPUs for it will probably have a high clock (only use clock as a measure for CPUs in the same series btw), handle non-SIMD operations well, and have a turbo boost mechanism. There aren't many Java-based benchmarks, but overall look for application benchmarks like compression and office. Don't look at gaming or media since those are affected greatly by SIMD. If you find a Java one, even better.
* * */3 * * that says, every minute of every hour on every three days.
0 0 */3 * * says at 00:00 (midnight) every three days.
try this html code
<md-input #myInput placeholder="Item name..." [(ngModel)]="name"></md-input>
<div *ngFor="let item of filteredItems | search: name">
{{item.name}}
</div>
use search pipe
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'search'
})
export class SearchPipe implements PipeTransform {
transform(value: any, args?: any): any {
if(!value)return null;
if(!args)return value;
args = args.toLowerCase();
return value.filter(function(item){
return JSON.stringify(item).toLowerCase().includes(args);
});
}
}
This answer, based on another one (link at end), is about the difference between two dates.
You can see how it works because it's simple, also it includes splitting the difference into
units of time (a function that I made) and converting to UTC to stop time zone problems.
function date_units_diff(a, b, unit_amounts) {_x000D_
var split_to_whole_units = function (milliseconds, unit_amounts) {_x000D_
// unit_amounts = list/array of amounts of milliseconds in a_x000D_
// second, seconds in a minute, etc., for example "[1000, 60]"._x000D_
time_data = [milliseconds];_x000D_
for (i = 0; i < unit_amounts.length; i++) {_x000D_
time_data.push(parseInt(time_data[i] / unit_amounts[i]));_x000D_
time_data[i] = time_data[i] % unit_amounts[i];_x000D_
}; return time_data.reverse();_x000D_
}; if (unit_amounts == undefined) {_x000D_
unit_amounts = [1000, 60, 60, 24];_x000D_
};_x000D_
var utc_a = new Date(a.toUTCString());_x000D_
var utc_b = new Date(b.toUTCString());_x000D_
var diff = (utc_b - utc_a);_x000D_
return split_to_whole_units(diff, unit_amounts);_x000D_
}_x000D_
_x000D_
// Example of use:_x000D_
var d = date_units_diff(new Date(2010, 0, 1, 0, 0, 0, 0), new Date()).slice(0,-2);_x000D_
document.write("In difference: 0 days, 1 hours, 2 minutes.".replace(_x000D_
/0|1|2/g, function (x) {return String( d[Number(x)] );} ));
_x000D_
A date/time difference, as milliseconds, can be calculated using the Date object:
var a = new Date(); // Current date now.
var b = new Date(2010, 0, 1, 0, 0, 0, 0); // Start of 2010.
var utc_a = new Date(a.toUTCString());
var utc_b = new Date(b.toUTCString());
var diff = (utc_b - utc_a); // The difference as milliseconds.
Then to work out the number of seconds in that difference, divide it by 1000 to convert
milliseconds to seconds, then change the result to an integer (whole number) to remove
the milliseconds (fraction part of that decimal): var seconds = parseInt(diff/1000)
.
Also, I could get longer units of time using the same process, for example:
- (whole) minutes, dividing seconds by 60 and changing the result to an integer,
- hours, dividing minutes by 60 and changing the result to an integer.
I created a function for doing that process of splitting the difference into
whole units of time, named split_to_whole_units
, with this demo:
console.log(split_to_whole_units(72000, [1000, 60]));
// -> [1,12,0] # 1 (whole) minute, 12 seconds, 0 milliseconds.
This answer is based on this other one.
Introduction to Algorithms: Second Edition by Cormen, Leiserson, Rivest & Stein says on page 44 that
Since any constant is a degree-0 polynomial, we can express any constant function as Theta(n^0), or Theta(1). This latter notation is a minor abuse, however, because it is not clear what variable is tending to infinity. We shall often use the notation Theta(1) to mean either a constant or a constant function with respect to some variable. ... We denote by O(g(n))... the set of functions f(n) such that there exist positive constants c and n0 such that 0 <= f(n) <= c*g(n) for all n >= n0. ... Note that f(n) = Theta(g(n)) implies f(n) = O(g(n)), since Theta notation is stronger than O notation.
If an algorithm runs in O(1) time, it means that asymptotically doesn't depend upon any variable, meaning that there exists at least one positive constant that when multiplied by one is greater than the asymptotic complexity (~runtime) of the function for values of n above a certain amount. Technically, it's O(n^0) time.
For small changes, I have used hexedit:
http://rigaux.org/hexedit.html
Simple but fast and useful.
IMPORTANT - on ubuntu package docker
is something entirely different ( avoid it ) :
issue following to view what if any packages you have mentioning docker
dpkg -l|grep docker
if only match is following then you do NOT have docker installed below is an unrelated package
docker - System tray for KDE3/GNOME2 docklet applications
if you see something similar to following then you have docker installed
dpkg -l|grep docker
ii docker-ce 5:19.03.13~3-0~ubuntu-focal amd64 Docker: the open-source application container engine
ii docker-ce-cli 5:19.03.13~3-0~ubuntu-focal amd64 Docker CLI: the open-source application container engine
NOTE - ubuntu package docker.io
is not getting updates ( obsolete do NOT use )
Instead do this : install the latest version of docker on linux by executing the following:
sudo curl -sSL https://get.docker.com/ | sh
# sudo curl -sSL https://test.docker.com | sh # get dev pipeline version
here is a typical output ( ubuntu 16.04 )
apparmor is enabled in the kernel and apparmor utils were already installed
+ sudo -E sh -c apt-key adv --keyserver hkp://ha.pool.sks-keyservers.net:80 --recv-keys 58118E89F3A912897C070ADBF76221572C52609D
Executing: /tmp/tmp.rAAGu0P85R/gpg.1.sh --keyserver
hkp://ha.pool.sks-keyservers.net:80
--recv-keys
58118E89F3A912897C070ADBF76221572C52609D
gpg: requesting key 2C52609D from hkp server ha.pool.sks-keyservers.net
gpg: key 2C52609D: "Docker Release Tool (releasedocker) <[email protected]>" 1 new signature
gpg: Total number processed: 1
gpg: new signatures: 1
+ break
+ sudo -E sh -c apt-key adv -k 58118E89F3A912897C070ADBF76221572C52609D >/dev/null
+ sudo -E sh -c mkdir -p /etc/apt/sources.list.d
+ dpkg --print-architecture
+ sudo -E sh -c echo deb [arch=amd64] https://apt.dockerproject.org/repo ubuntu-xenial main > /etc/apt/sources.list.d/docker.list
+ sudo -E sh -c sleep 3; apt-get update; apt-get install -y -q docker-engine
Hit:1 http://repo.steampowered.com/steam precise InRelease
Hit:2 http://download.virtualbox.org/virtualbox/debian xenial InRelease
Ign:3 http://dl.google.com/linux/chrome/deb stable InRelease
Hit:4 http://dl.google.com/linux/chrome/deb stable Release
Hit:5 http://archive.canonical.com/ubuntu xenial InRelease
Hit:6 http://mirror.cc.columbia.edu/pub/linux/ubuntu/archive xenial InRelease
Hit:7 http://mirror.cc.columbia.edu/pub/linux/ubuntu/archive xenial-updates InRelease
Hit:8 http://ppa.launchpad.net/me-davidsansome/clementine/ubuntu xenial InRelease
Ign:9 http://repo.mongodb.org/apt/debian wheezy/mongodb-org/3.2 InRelease
Hit:10 http://mirror.cc.columbia.edu/pub/linux/ubuntu/archive xenial-backports InRelease
Hit:11 http://repo.mongodb.org/apt/debian wheezy/mongodb-org/3.2 Release
Hit:12 http://mirror.cc.columbia.edu/pub/linux/ubuntu/archive xenial-security InRelease
Hit:14 http://ppa.launchpad.net/numix/ppa/ubuntu xenial InRelease
Ign:15 http://linux.dropbox.com/ubuntu wily InRelease
Ign:16 http://repo.vivaldi.com/stable/deb stable InRelease
Hit:17 http://repo.vivaldi.com/stable/deb stable Release
Get:18 http://linux.dropbox.com/ubuntu wily Release [6,596 B]
Get:19 https://apt.dockerproject.org/repo ubuntu-xenial InRelease [20.6 kB]
Ign:20 http://packages.amplify.nginx.com/ubuntu xenial InRelease
Hit:22 http://packages.amplify.nginx.com/ubuntu xenial Release
Hit:23 https://deb.opera.com/opera-beta stable InRelease
Hit:26 https://deb.opera.com/opera-developer stable InRelease
Get:28 https://apt.dockerproject.org/repo ubuntu-xenial/main amd64 Packages [1,719 B]
Hit:29 https://packagecloud.io/slacktechnologies/slack/debian jessie InRelease
Fetched 28.9 kB in 1s (17.2 kB/s)
Reading package lists... Done
W: http://repo.mongodb.org/apt/debian/dists/wheezy/mongodb-org/3.2/Release.gpg: Signature by key 42F3E95A2C4F08279C4960ADD68FA50FEA312927 uses weak digest algorithm (SHA1)
Reading package lists...
Building dependency tree...
Reading state information...
The following additional packages will be installed:
aufs-tools cgroupfs-mount
The following NEW packages will be installed:
aufs-tools cgroupfs-mount docker-engine
0 upgraded, 3 newly installed, 0 to remove and 17 not upgraded.
Need to get 14.6 MB of archives.
After this operation, 73.7 MB of additional disk space will be used.
Get:1 http://mirror.cc.columbia.edu/pub/linux/ubuntu/archive xenial/universe amd64 aufs-tools amd64 1:3.2+20130722-1.1ubuntu1 [92.9 kB]
Get:2 http://mirror.cc.columbia.edu/pub/linux/ubuntu/archive xenial/universe amd64 cgroupfs-mount all 1.2 [4,970 B]
Get:3 https://apt.dockerproject.org/repo ubuntu-xenial/main amd64 docker-engine amd64 1.11.2-0~xenial [14.5 MB]
Fetched 14.6 MB in 7s (2,047 kB/s)
Selecting previously unselected package aufs-tools.
(Reading database ... 427978 files and directories currently installed.)
Preparing to unpack .../aufs-tools_1%3a3.2+20130722-1.1ubuntu1_amd64.deb ...
Unpacking aufs-tools (1:3.2+20130722-1.1ubuntu1) ...
Selecting previously unselected package cgroupfs-mount.
Preparing to unpack .../cgroupfs-mount_1.2_all.deb ...
Unpacking cgroupfs-mount (1.2) ...
Selecting previously unselected package docker-engine.
Preparing to unpack .../docker-engine_1.11.2-0~xenial_amd64.deb ...
Unpacking docker-engine (1.11.2-0~xenial) ...
Processing triggers for libc-bin (2.23-0ubuntu3) ...
Processing triggers for man-db (2.7.5-1) ...
Processing triggers for ureadahead (0.100.0-19) ...
Processing triggers for systemd (229-4ubuntu6) ...
Setting up aufs-tools (1:3.2+20130722-1.1ubuntu1) ...
Setting up cgroupfs-mount (1.2) ...
Setting up docker-engine (1.11.2-0~xenial) ...
Processing triggers for libc-bin (2.23-0ubuntu3) ...
Processing triggers for systemd (229-4ubuntu6) ...
Processing triggers for ureadahead (0.100.0-19) ...
+ sudo -E sh -c docker version
Client:
Version: 1.11.2
API version: 1.23
Go version: go1.5.4
Git commit: b9f10c9
Built: Wed Jun 1 22:00:43 2016
OS/Arch: linux/amd64
Server:
Version: 1.11.2
API version: 1.23
Go version: go1.5.4
Git commit: b9f10c9
Built: Wed Jun 1 22:00:43 2016
OS/Arch: linux/amd64
If you would like to use Docker as a non-root user, you should now consider
adding your user to the "docker" group with something like:
sudo usermod -aG docker stens
Remember that you will have to log out and back in for this to take effect!
Here is the underlying detailed install instructions which as you can see comes bundled into above technique ... Above one liner gives you same as :
https://docs.docker.com/engine/installation/linux/ubuntulinux/
Once installed you can see what docker packages were installed by issuing
dpkg -l|grep docker
ii docker-ce 5:19.03.13~3-0~ubuntu-focal amd64 Docker: the open-source application container engine
ii docker-ce-cli 5:19.03.13~3-0~ubuntu-focal amd64 Docker CLI: the open-source application container engine
now Docker updates will get installed going forward when you issue
sudo apt-get update
sudo apt-get upgrade
take a look at
ls -latr /etc/apt/sources.list.d/*docker*
-rw-r--r-- 1 root root 202 Jun 23 10:01 /etc/apt/sources.list.d/docker.list.save
-rw-r--r-- 1 root root 71 Jul 4 11:32 /etc/apt/sources.list.d/docker.list
cat /etc/apt/sources.list.d/docker.list
deb [arch=amd64] https://apt.dockerproject.org/repo ubuntu-xenial main
or more generally
cd /etc/apt
grep -r docker *
sources.list.d/docker.list:deb [arch=amd64] https://download.docker.com/linux/ubuntu focal test
You can use gridspec
and figure
:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import gridspec
# generate some data
x = np.arange(0, 10, 0.2)
y = np.sin(x)
# plot it
fig = plt.figure(figsize=(8, 6))
gs = gridspec.GridSpec(1, 2, width_ratios=[3, 1])
ax0 = plt.subplot(gs[0])
ax0.plot(x, y)
ax1 = plt.subplot(gs[1])
ax1.plot(y, x)
plt.tight_layout()
plt.savefig('grid_figure.pdf')
ngRoute is part of the core AngularJS framework.
ui-router is a community library that has been created to attempt to improve upon the default routing capabilities.
Here is a good article about configuring/setting up ui-router:
It is 2019 and I need to sign APK with V1 (jar signature) or V2 (full APK signature). I googled "generate signed apk gradle" and it brought me here. So I am adding my original solution here.
signingConfigs {
release {
...
v1SigningEnabled true
v2SigningEnabled true
}
}
My original question: How to use V1 (Jar signature) or V2 (Full APK signature) from build.gradle file
-mmin is for minutes.
Try looking at the man page.
man find
for more types.
The properties that can be set for a figure
is referenced here.
You could then use:
figure_number = 1;
x = 0; % Screen position
y = 0; % Screen position
width = 600; % Width of figure
height = 400; % Height of figure (by default in pixels)
figure(figure_number, 'Position', [x y width height]);
In the following link you can find useful info about recording with AVAudioRecording. In this link in the first part "USing Audio" there is an anchor named “Recording with the AVAudioRecorder Class.” that leads you to the example.
If you are getting a JS based date String
then first use the new Date(String)
constructor and then pass the Date
object to the moment
method. Like:
var dateString = 'Thu Jul 15 2016 19:31:44 GMT+0200 (CEST)';
var dateObj = new Date(dateString);
var momentObj = moment(dateObj);
var momentString = momentObj.format('YYYY-MM-DD'); // 2016-07-15
In case dateString
is 15-07-2016
, then you should use the moment(date:String, format:String)
method
var dateString = '07-15-2016';
var momentObj = moment(dateString, 'MM-DD-YYYY');
var momentString = momentObj.format('YYYY-MM-DD'); // 2016-07-15
Unfortunately none of the suggestions helped me, but after some more googling this
pip install aenum
solved it for me
When using javascript:
in navigation the return value of the executed script, if there is one, becomes the content of a new document which is displayed in the browser. The void
operator in JavaScript causes the return value of the expression following it to return undefined, which prevents this action from happening. You can try it yourself, copy the following into the address bar and press return:
javascript:"hello"
The result is a new page with only the word "hello". Now change it to:
javascript:void "hello"
...nothing happens.
When you write javascript:
on its own there's no script being executed, so the result of that script execution is also undefined, so the browser does nothing. This makes the following more or less equivalent:
javascript:undefined;
javascript:void 0;
javascript:
With the exception that undefined can be overridden by declaring a variable with the same name. Use of void 0
is generally pointless, and it's basically been whittled down from void functionThatReturnsSomething()
.
As others have mentioned, it's better still to use return false;
in the click handler than use the javascript:
protocol.
Why don't you do something like this?
<View
style={{
borderBottomWidth: 1,
borderBottomColor: 'black',
width: 400,
}}
/>
According to the React Documentation it's perfectly OK to call setState()
from within the componentDidMount()
function.
It will cause render()
to be called twice, which is less efficient than only calling it once, but other than that it's perfectly fine.
You can find the documentation here:
https://reactjs.org/docs/react-component.html#componentdidmount
Here is the excerpt from the documentation:
You may call setState() immediately in componentDidMount(). It will trigger an extra rendering, but it will happen before the browser updates the screen. This guarantees that even though the render() will be called twice in this case, the user won’t see the intermediate state. Use this pattern with caution because it often causes performance issues...
Using html5 doctype at the beginning of the page.
<!DOCTYPE html>
Force IE to use the latest render mode
<meta http-equiv="X-UA-Compatible" content="IE=edge">
If your target browser is ie8, then check your compatible settings in IE8
All answers posted so far are giving the right solutions, however no one answer was able to properly explain the underlying cause of the concrete problem.
Facelets is a XML based view technology which uses XHTML+XML to generate HTML output. XML has five special characters which has special treatment by the XML parser:
<
the start of a tag.>
the end of a tag."
the start and end of an attribute value.'
the alternative start and end of an attribute value.&
the start of an entity (which ends with ;
).In case of &
which is not followed by #
(e.g.  
,  
, etc), the XML parser is implicitly looking for one of the five predefined entity names lt
, gt
, amp
, quot
and apos
, or any manually defined entity name. However, in your particular case, you was using &
as a JavaScript operator, not as an XML entity. This totally explains the XML parsing error you got:
The entity name must immediately follow the '&' in the entity reference
In essence, you're writing JavaScript code in the wrong place, a XML document instead of a JS file, so you should be escaping all XML special characters accordingly. The &
must be escaped as &
.
So, in your particular case, the
if (Modernizr.canvas && Modernizr.localstorage &&
must become
if (Modernizr.canvas && Modernizr.localstorage &&
to make it XML-valid.
However, this makes the JavaScript code harder to read and maintain. As stated in Mozilla Developer Network's excellent document Writing JavaScript for XHTML, you should be placing the JavaScript code in a character data (CDATA) block. Thus, in JSF terms, that would be:
<h:outputScript>
<![CDATA[
// ...
]]>
</h:outputScript>
The XML parser will interpret the block's contents as "plain vanilla" character data and not as XML and hence interpret the XML special characters "as-is".
But, much better is to just put the JS code in its own JS file which you include by <script src>
, or in JSF terms, the <h:outputScript>
.
<h:outputScript name="onload.js" target="body" />
(note the target="body"
; this way JSF will automatically render the <script>
at the very end of <body>
, regardless of where <h:outputScript>
itself is located, hereby achieving the same effect as with window.onload
and $(document).ready()
; so you don't need to use those anymore in that script)
This way you don't need to worry about XML-special characters in your JS code. As an additional bonus, this gives you the opportunity to let the browser cache the JS file so that total response size is smaller.
When I try:
<input type="button" id="moreFields" onclick="alert('The text will be show!!'); return false;" value="Give me more fields!" />
It's worked well. So I think the problem is position of moreFields() function. Ensure that function will be define before your input tag.
Pls try:
<script type="text/javascript">
function moreFields() {
alert("The text will be show");
}
</script>
<input type="button" id="moreFields" onclick="moreFields()" value="Give me more fields!" />
Hope it helped.
The best way to get rid on it is adding or modifying the data-interval attribute like this:
<div data-ride="carousel" class="carousel slide" data-interval="10000" id="myCarousel">
It's specified on ms like it's usually on js, so 1000 = 1s, 3000 = 3s... 10000 = 10s.
By the way you can also specify it at 0 for not sliding automatically. It's useful when showing product images on mobile for example.
<div data-ride="carousel" class="carousel slide" data-interval="0" id="myCarousel">
Your file seems quite small (297 lines) so you can read and write them quite quickly. You refer to Excel CSV, which does not exists, and you show space delimited data in your example. Furthermore, Access is limited to 255 columns, and a CSV is not, so there is no guarantee this will work
Sub StripHeaderAndFooter()
Dim fs As Object ''FileSystemObject
Dim tsIn As Object, tsOut As Object ''TextStream
Dim sFileIn As String, sFileOut As String
Dim aryFile As Variant
sFileIn = "z:\docs\FileName.csv"
sFileOut = "z:\docs\FileOut.csv"
Set fs = CreateObject("Scripting.FileSystemObject")
Set tsIn = fs.OpenTextFile(sFileIn, 1) ''ForReading
sTmp = tsIn.ReadAll
Set tsOut = fs.CreateTextFile(sFileOut, True) ''Overwrite
aryFile = Split(sTmp, vbCrLf)
''Start at line 3 and end at last line -1
For i = 3 To UBound(aryFile) - 1
tsOut.WriteLine aryFile(i)
Next
tsOut.Close
DoCmd.TransferText acImportDelim, , "NewCSV", sFileOut, False
End Sub
Edit re various comments
It is possible to import a text file manually into MS Access and this will allow you to choose you own cell delimiters and text delimiters. You need to choose External data from the menu, select your file and step through the wizard.
About importing and linking data and database objects -- Applies to: Microsoft Office Access 2003
Introduction to importing and exporting data -- Applies to: Microsoft Access 2010
Once you get the import working using the wizards, you can save an import specification and use it for you next DoCmd.TransferText as outlined by @Olivier Jacot-Descombes. This will allow you to have non-standard delimiters such as semi colon and single-quoted text.
As long as the server allows the ampresand character to be POSTed (not all do as it can be unsafe), all you should have to do is URL Encode the character. In the case of an ampresand, you should replace the character with %26
.
.NET provides a nice way of encoding the entire string for you though:
string strNew = "&uploadfile=true&file=" + HttpUtility.UrlEncode(iCalStr);
You can include a .js file which has the script to set the
window.location.href = url;
Where url would be the url you wish to load.
I think we can write this fewer styles, without changing the existing color. The following worked for me (in Bootstrap 3.2.0)
.navbar-nav > li > a { padding-top: 5px !important; padding-bottom: 5px !important; }
.navbar { min-height: 32px !important; }
.navbar-brand { padding-top: 5px; padding-bottom: 10px; padding-left: 10px; }
The last one ('navbar-brand') is actually needed only if you have text as your 'brand' name.
From perlfaq8:
How can I sleep() or alarm() for under a second?
If you want finer granularity than the 1 second that the sleep() function provides, the easiest way is to use the select() function as documented in select in perlfunc. Try the Time::HiRes and the BSD::Itimer modules (available from CPAN, and starting from Perl 5.8 Time::HiRes is part of the standard distribution).
Separate function to make adding event handlers much easier.
function addListener(event, obj, fn) {
if (obj.addEventListener) {
obj.addEventListener(event, fn, false); // modern browsers
} else {
obj.attachEvent("on"+event, fn); // older versions of IE
}
}
element = document.getElementsByClassName('drill_cursor')[0];
addListener('click', element, function () {
// Do stuff
});
Courtesy of this page, I found this worked when the suggestions above didn't:
import PIL.Image
from cStringIO import StringIO
import IPython.display
import numpy as np
def showarray(a, fmt='png'):
a = np.uint8(a)
f = StringIO()
PIL.Image.fromarray(a).save(f, fmt)
IPython.display.display(IPython.display.Image(data=f.getvalue()))
Another streaming command I've had good results with is piping the ffmpeg output to vlc to create a stream. If you don't have these installed, you can add them:
sudo apt install vlc ffmpeg
In the example I use an mpeg transport stream (ts) over http, instead of rtsp. I've tried both, but the http ts stream seems to work glitch-free on my playback devices.
I'm using a video capture HDMI>USB device that sets itself up on the video4linux2 driver as input. Piping through vlc must be CPU-friendly, because my old dual-core Pentium CPU is able to do the real-time encoding with no dropped frames. I've also had audio-sync issues with some of the other methods, where this method always has perfect audio-sync.
You will have to adjust the command for your device or file. If you're using a file as input, you won't need all that v4l2 and alsa stuff. Here's the ffmpeg|vlc command:
ffmpeg -thread_queue_size 1024 -f video4linux2 -input_format mjpeg -i /dev/video0 -r 30 -f alsa -ac 1 -thread_queue_size 1024 -i hw:1,0 -acodec aac -vcodec libx264 -preset ultrafast -crf 18 -s hd720 -vf format=yuv420p -profile:v main -threads 0 -f mpegts -|vlc -I dummy - --sout='#std{access=http,mux=ts,dst=:8554}'
For example, lets say your server PC IP is 192.168.0.10, then the stream can be played by this command:
ffplay http://192.168.0.10:8554
#or
vlc http://192.168.0.10:8554
I know you've found a solution to your question, I just wanted to recommend that maybe you look at the following more extensive jQuery plugin for International Number Formats:
After a recent update on my Ubuntu 16.04 system I have also started getting this error when trying to run convert on .ps files to convert them into pdfs.
This fix worked for me:
In a terminal run:
sudo gedit /etc/ImageMagick-6/policy.xml
This should open the policy.xml file in the gedit text editor. If it doesn't, your image magick might be installed in a different place. Then change
rights="none"
to
rights="read | write"
for PDF, EPS and PS lines near the bottom of the file. Save and exit, and image magick should then work again.
sed -i '/^$/d' foo
This tells sed
to delete every line matching the regex ^$
i.e. every empty line. The -i
flag edits the file in-place, if your sed
doesn't support that you can write the output to a temporary file and replace the original:
sed '/^$/d' foo > foo.tmp
mv foo.tmp foo
If you also want to remove lines consisting only of whitespace (not just empty lines) then use:
sed -i '/^[[:space:]]*$/d' foo
Edit: also remove whitespace at the end of lines, because apparently you've decided you need that too:
sed -i '/^[[:space:]]*$/d;s/[[:space:]]*$//' foo
You have a basic answer here: Get city name using geolocation
But for what you are looking for, i'd recommend this way.
Only if you also need administrative_area_level_1,to store different things for Paris, Texas, US and Paris, Ile-de-France, France and provide a manual fallback:
--
There is a problem in Michal's way, in that it takes the first result, not a particular one. He uses results[0]. The way I see fit (I just modified his code) is to take ONLY the result whose type is "locality", which is always present, even in an eventual manual fallback in case the browser does not support geolocation.
His way: fetched results are different from using http://maps.googleapis.com/maps/api/geocode/json?address=bucharest&sensor=false than from using http://maps.googleapis.com/maps/api/geocode/json?latlng=44.42514,26.10540&sensor=false (searching by name / searching by lat&lng)
This way: same fetched results.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Reverse Geocoding</title>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var geocoder;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
}
//Get the latitude and the longitude;
function successFunction(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
codeLatLng(lat, lng)
}
function errorFunction(){
alert("Geocoder failed");
}
function initialize() {
geocoder = new google.maps.Geocoder();
}
function codeLatLng(lat, lng) {
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
//console.log(results);
if (results[1]) {
var indice=0;
for (var j=0; j<results.length; j++)
{
if (results[j].types[0]=='locality')
{
indice=j;
break;
}
}
alert('The good number is: '+j);
console.log(results[j]);
for (var i=0; i<results[j].address_components.length; i++)
{
if (results[j].address_components[i].types[0] == "locality") {
//this is the object you are looking for City
city = results[j].address_components[i];
}
if (results[j].address_components[i].types[0] == "administrative_area_level_1") {
//this is the object you are looking for State
region = results[j].address_components[i];
}
if (results[j].address_components[i].types[0] == "country") {
//this is the object you are looking for
country = results[j].address_components[i];
}
}
//city data
alert(city.long_name + " || " + region.long_name + " || " + country.short_name)
} else {
alert("No results found");
}
//}
} else {
alert("Geocoder failed due to: " + status);
}
});
}
</script>
</head>
<body onload="initialize()">
</body>
</html>
#Footer {
position:fixed;
bottom:0;
width:100%;
}
worked for me
Since explode()
returns an array, you can add square brackets directly to the end of that function, if you happen to know the position of the last array item.
$email = '[email protected]';
$provider = explode('@', $email)[1];
echo $provider; // example.com
Or another way is list()
:
$email = '[email protected]';
list($prefix, $provider) = explode('@', $email);
echo $provider; // example.com
If you don't know the position:
$path = 'one/two/three/four';
$dirs = explode('/', $path);
$last_dir = $dirs[count($dirs) - 1];
echo $last_dir; // four
You dont need to give column names manually in xaml. Just set AutoGenerateColumns property to true and your list will be automatically binded to DataGrid. refer code. XAML Code:
<Grid>
<DataGrid x:Name="MyDatagrid" AutoGenerateColumns="True" Height="447" HorizontalAlignment="Left" Margin="20,85,0,0" VerticalAlignment="Top" Width="799" ItemsSource="{Binding Path=ListTest, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" CanUserAddRows="False"> </Grid>
C#
Public Class Test
{
public string m_field1_Test{get;set;}
public string m_field2_Test { get; set; }
public Test()
{
m_field1_Test = "field1";
m_field2_Test = "field2";
}
public MainWindow()
{
listTest = new List<Test>();
for (int i = 0; i < 10; i++)
{
obj = new Test();
listTest.Add(obj);
}
this.MyDatagrid.ItemsSource = ListTest;
InitializeComponent();
}
Default to using the built in System.Text.Json
parser implementation.
e.g.
using System.Text.Json;
var json = JsonSerializer.Serialize(aList);
alternatively, other, less mainstream options are available like Utf8Json parser and Jil: These may offer superior performance, if you really need it but, you will need to install their respective packages.
Default to using Newtonsoft JSON.Net as your first choice JSON Parser.
e.g.
using Newtonsoft.Json;
var json = JsonConvert.SerializeObject(aList);
you may need to install the package first.
PM> Install-Package Newtonsoft.Json
For more details see and upvote the answer that is the source of this information.
// you need to reference System.Web.Extensions
using System.Web.Script.Serialization;
var jsonSerialiser = new JavaScriptSerializer();
var json = jsonSerialiser.Serialize(aList);
You can import svg and it use it like a image
import chatSVG from '../assets/images/undraw_typing_jie3.svg'
And ise it in img tag
<img src={chatSVG} className='iconChat' alt="Icon chat"/>
InOrder
helps you to do that.
ServiceClassA firstMock = mock(ServiceClassA.class);
ServiceClassB secondMock = mock(ServiceClassB.class);
Mockito.doNothing().when(firstMock).methodOne();
Mockito.doNothing().when(secondMock).methodTwo();
//create inOrder object passing any mocks that need to be verified in order
InOrder inOrder = inOrder(firstMock, secondMock);
//following will make sure that firstMock was called before secondMock
inOrder.verify(firstMock).methodOne();
inOrder.verify(secondMock).methodTwo();
I don't know about javax.media.j3d, so I might be mistaken, but you usually want to investigate whether there is a memory leak. Well, as others note, if it was 64MB and you are doing something with 3d, maybe it's obviously too small...
But if I were you, I'll set up a profiler or visualvm, and let your application run for extended time (days, weeks...). Then look at the heap allocation history, and make sure it's not a memory leak.
If you use a profiler, like JProfiler or the one that comes with NetBeans IDE etc., you can see what object is being accumulating, and then track down what's going on.. Well, almost always something is incorrectly not removed from a collection...
Another base solution
group_sorted <- group[order(group$Subject, -group$pt),]
group_sorted[!duplicated(group_sorted$Subject),]
# Subject pt Event
# 1 5 2
# 2 17 2
# 3 5 2
Order the data frame by pt
(descending) and then remove rows duplicated in Subject