This answer is for those google searchers who want to show dotted bottom border of EditText
like here
Create dotted.xml
inside drawable
folder and paste these
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:bottom="1dp"
android:left="-2dp"
android:right="-2dp"
android:top="-2dp">
<shape android:shape="rectangle">
<stroke
android:width="0.5dp"
android:color="@android:color/black" />
<solid android:color="#ffffff" />
<stroke
android:width="1dp"
android:color="#030310"
android:dashGap="5dp"
android:dashWidth="5dp" />
<padding
android:bottom="5dp"
android:left="5dp"
android:right="5dp"
android:top="5dp" />
</shape>
</item>
</layer-list>
Then simply set the android:background
attribute to dotted.xml
we just created. Your EditText
looks like this.
<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Some Text"
android:background="@drawable/dotted" />
Thanks for all the helpful info. It turns out that my host changed servers and started using a different session save path other than /var/php_sessions which didn't exist anymore. A solution would have been to declare ini_set(' session.save_path','SOME WRITABLE PATH');
in all my script files but that would have been a pain. I talked with the host and they explicitly set the session path to a real path that did exist. Hope this helps anyone having session path troubles.
You are floating the children which means they "float" in front of the container. In order to take the correct height, you must "clear" the float
The div style="clear: both" clears the floating an gives the correct height to the container. see http://css.maxdesign.com.au/floatutorial/clear.htm for more info on floats.
eg.
<div class="c">
<div class="l">
</div>
<div class="m">
World
</div>
<div style="clear: both" />
</div>
Wouldn't it be as simple as
0 < 5 && 5 < 10
?
So I suppose if you want a function out of it you could simply add this to a utility class:
public static bool Between(int num, int min, int max) {
return min < num && num < max;
}
In my case the issue was a missing 's' in the HTTP URL. Error was: "HttpHostConnectException: Connect to someendpoint.com:80 [someendpoint.com/127.0.0.1] failed: Connection refused" End point and IP obviously changed to protect the network.
After running around in the Preferences dialog, the following is the location at which the highlight color for "occurrences" can be changed:
General -> Editors -> Text Editors -> Annotations
Look for Occurences
from the Annotation types list.
Then, be sure that Text as highlighted
is selected, then choose the desired color.
And, a picture is worth a thousand words...
(source: coobird.net)
(source: coobird.net)
You should try using maven failsafe plugin. You can tell it to include a certain set of tests.
I have found that in Font-Awesome version 5 (free), you have you add: "font-family: Font Awesome\ 5 Free;" only then it seems to be working properly.
This has worked for me :)
I hope some finds this helpful
Uses a "standard" set of character orderings (a,b,c, ... etc.). This is in contrast to some specific locales, which may sort characters in different orders ('a-with-acute' may be before or after 'a', depending on the locale, and so on).
On the other hand, looks purely at the values of the raw byte(s) that represent the character.
There's a great sample at http://msdn.microsoft.com/en-us/library/e6883c06.aspx that shows the results of the various StringComparison values. All the way at the end, it shows (excerpted):
StringComparison.InvariantCulture:
LATIN SMALL LETTER I (U+0069) is less than LATIN SMALL LETTER DOTLESS I (U+0131)
LATIN SMALL LETTER I (U+0069) is less than LATIN CAPITAL LETTER I (U+0049)
LATIN SMALL LETTER DOTLESS I (U+0131) is greater than LATIN CAPITAL LETTER I (U+0049)
StringComparison.Ordinal:
LATIN SMALL LETTER I (U+0069) is less than LATIN SMALL LETTER DOTLESS I (U+0131)
LATIN SMALL LETTER I (U+0069) is greater than LATIN CAPITAL LETTER I (U+0049)
LATIN SMALL LETTER DOTLESS I (U+0131) is greater than LATIN CAPITAL LETTER I (U+0049)
You can see that where InvariantCulture yields (U+0069, U+0049, U+00131), Ordinal yields (U+0049, U+0069, U+00131).
I was trying to write a code that would work on both Mac and Windows. The code was working fine on Windows, but was giving the response as 'Unsupported Media Type' on Mac. Here is the code I used and the following line made the code work on Mac as well:
Request.AddHeader "Content-Type", "application/json"
Here is the snippet of my code:
Dim Client As New WebClient
Dim Request As New WebRequest
Dim Response As WebResponse
Dim Distance As String
Client.BaseUrl = "http://1.1.1.1:8080/config"
Request.AddHeader "Content-Type", "application/json" *** The line that made the code work on mac
Set Response = Client.Execute(Request)
As @Vlad from Moscow says,
Take into account that value_type
for std::map
is defined the following way:
typedef pair<const Key, T> value_type
This then means that if you wish to replace the keyword auto
with a more explicit type specifier, then you could this;
for ( const pair<const string, int> &p : table ) {
std::cout << p.first << '\t' << p.second << std::endl;
}
Just for understanding what auto
will translate to in this case.
On my machine:
C:\Program Files\PostgreSQL\8.4\data\postgresql.conf
Let me add my 2¢, it's my job to get good and clean data for a hedge-fund, I've seen quite a lot of data feeds and historical data providers. This is mainly about US stock data.
To start with, if you have some money don't bother with downloading data from Yahoo, get the end of day data straight from CSI data, this is where Yahoo gets their EOD data as well AFAIK. They have an API where you can extract the data to whatever format you want. I think the yearly subscription for data is a few $100 bucks.
The main problem with downloading data from a free service is that you only get stocks that still exist, this is called Survivorship Bias and can give you wrong results if you look at many stocks, because you'll only include the ones that made it so far and not the ones that were de-listed.
For playing around with some intraday data I'd look into IQFeed, they provide several APIs to extract historical data, although they are mainly an outfit for real-time feeds. But here there are quite a few options, some brokers even provide historical data downloads via their APIs, so just pick your poison.
BUT usually all of this data is not very clean, once you really start back testing you'll see that certain stocks are missing or appear as two different symbols, or stock splits are not properly accounted for, etc. And then you realize that historical dividend data is need as well and so you start running in circles, patching data together from 100 different data sources and so on. So to start with a "discount" data feed will do, but as soon as you run more comprehensive backtests you might run into problems depending on what you do. If you just look at, let's say, the S&P 500 stocks this will not be so much a problem though and a "cheap" intraday feed will do.
What you will not find is free intraday data. I mean you might find some examples, I'm sure there's somewhere 5 years of MSFT tick data floating around but that will not get you very far.
Then, if you need the real stuff (level II order book, all ticks as they have happened at all exchanges) one "affordable", yet excellent option is Nanex. They'll actually ship you a drive with terabytes of data. If I remember right its about $3k-4K per year of data. But trust me, once you understand how hard it is to get good intraday data, you won't think this is very much money at all.
Not to discourage you but to get good data is hard, so hard in fact that many hedge-funds and banks spend hundreds of thousands of dollars a month to get data they can trust. Again, you can start somewhere and then go from there but it's good to see it a bit in context.
Edit: The answer above is from my own experience. This write-up from Caltech about available data feeds will give more insights, and especially recommends QuantQuote.
There are several ways to simulate default parameters in Java:
Method overloading.
void foo(String a, Integer b) {
//...
}
void foo(String a) {
foo(a, 0); // here, 0 is a default value for b
}
foo("a", 2);
foo("a");
One of the limitations of this approach is that it doesn't work if you have two optional parameters of the same type and any of them can be omitted.
Varargs.
a) All optional parameters are of the same type:
void foo(String a, Integer... b) {
Integer b1 = b.length > 0 ? b[0] : 0;
Integer b2 = b.length > 1 ? b[1] : 0;
//...
}
foo("a");
foo("a", 1, 2);
b) Types of optional parameters may be different:
void foo(String a, Object... b) {
Integer b1 = 0;
String b2 = "";
if (b.length > 0) {
if (!(b[0] instanceof Integer)) {
throw new IllegalArgumentException("...");
}
b1 = (Integer)b[0];
}
if (b.length > 1) {
if (!(b[1] instanceof String)) {
throw new IllegalArgumentException("...");
}
b2 = (String)b[1];
//...
}
//...
}
foo("a");
foo("a", 1);
foo("a", 1, "b2");
The main drawback of this approach is that if optional parameters are of different types you lose static type checking. Furthermore, if each parameter has different meaning you need some way to distinguish them.
Nulls. To address the limitations of the previous approaches you can allow null values and then analyse each parameter in a method body:
void foo(String a, Integer b, Integer c) {
b = b != null ? b : 0;
c = c != null ? c : 0;
//...
}
foo("a", null, 2);
Now all arguments values must be provided, but the default ones may be null.
Optional class. This approach is similar to nulls, but uses Java 8 Optional class for parameters that have a default value:
void foo(String a, Optional<Integer> bOpt) {
Integer b = bOpt.isPresent() ? bOpt.get() : 0;
//...
}
foo("a", Optional.of(2));
foo("a", Optional.<Integer>absent());
Optional makes a method contract explicit for a caller, however, one may find such signature too verbose.
Builder pattern. The builder pattern is used for constructors and is implemented by introducing a separate Builder class:
class Foo {
private final String a;
private final Integer b;
Foo(String a, Integer b) {
this.a = a;
this.b = b;
}
//...
}
class FooBuilder {
private String a = "";
private Integer b = 0;
FooBuilder setA(String a) {
this.a = a;
return this;
}
FooBuilder setB(Integer b) {
this.b = b;
return this;
}
Foo build() {
return new Foo(a, b);
}
}
Foo foo = new FooBuilder().setA("a").build();
Maps. When the number of parameters is too large and for most of them default values are usually used, you can pass method arguments as a map of their names/values:
void foo(Map<String, Object> parameters) {
String a = "";
Integer b = 0;
if (parameters.containsKey("a")) {
if (!(parameters.get("a") instanceof Integer)) {
throw new IllegalArgumentException("...");
}
a = (String)parameters.get("a");
} else if (parameters.containsKey("b")) {
//...
}
//...
}
foo(ImmutableMap.<String, Object>of(
"a", "a",
"b", 2,
"d", "value"));
Please note that you can combine any of these approaches to achieve a desirable result.
This answer has not been given yet so I thought I'd post it. I looked all around the web, and didn't find a good answer for testing favicons in local development.
In current version of chrome (on OSX) if you do the following you will get an instant favicon refresh:
This is the easiest way I've found to refresh the favicon locally.
Default values are only used if the arguments are not specified. In your case you did specify the arguments - both were supplied, with a value of NULL. (Yes, in this case NULL is considered a real value :-). Try:
EXEC TEST()
Share and enjoy.
Addendum: The default values for procedure parameters are certainly buried in a system table somewhere (see the SYS.ALL_ARGUMENTS
view), but getting the default value out of the view involves extracting text from a LONG field, and is probably going to prove to be more painful than it's worth. The easy way is to add some code to the procedure:
CREATE OR REPLACE PROCEDURE TEST(X IN VARCHAR2 DEFAULT 'P',
Y IN NUMBER DEFAULT 1)
AS
varX VARCHAR2(32767) := NVL(X, 'P');
varY NUMBER := NVL(Y, 1);
BEGIN
DBMS_OUTPUT.PUT_LINE('X=' || varX || ' -- ' || 'Y=' || varY);
END TEST;
When you define a function, you also define what info (arguments) that function needs to work. If it is designed to work without any additional info, and you pass it some, you are going to get that error.
Example: Takes no arguments:
def dog
end
Takes arguments:
def cat(name)
end
When you call these, you need to call them with the arguments you defined.
dog #works fine
cat("Fluffy") #works fine
dog("Fido") #Returns ArgumentError (1 for 0)
cat #Returns ArgumentError (0 for 1)
Check out the Ruby Koans to learn all this.
To get the type of fields in struct
package main
import (
"fmt"
"reflect"
)
type testObject struct {
Name string
Age int
Height float64
}
func main() {
tstObj := testObject{Name: "yog prakash", Age: 24, Height: 5.6}
val := reflect.ValueOf(&tstObj).Elem()
typeOfTstObj := val.Type()
for i := 0; i < val.NumField(); i++ {
fieldType := val.Field(i)
fmt.Printf("object field %d key=%s value=%v type=%s \n",
i, typeOfTstObj.Field(i).Name, fieldType.Interface(),
fieldType.Type())
}
}
Output
object field 0 key=Name value=yog prakash type=string
object field 1 key=Age value=24 type=int
object field 2 key=Height value=5.6 type=float64
See in IDE https://play.golang.org/p/bwIpYnBQiE
You can read a CSV file with headers into a NumPy structured array with np.genfromtxt. For example:
import numpy as np
csv_fname = 'file.csv'
with open(csv_fname, 'w') as fp:
fp.write("""\
"A","B","C","D","E","F","timestamp"
611.88243,9089.5601,5133.0,864.07514,1715.37476,765.22777,1.291111964948E12
611.88243,9089.5601,5133.0,864.07514,1715.37476,765.22777,1.291113113366E12
611.88243,9089.5601,5133.0,864.07514,1715.37476,765.22777,1.291120650486E12
""")
# Read the CSV file into a Numpy record array
r = np.genfromtxt(csv_fname, delimiter=',', names=True, case_sensitive=True)
print(repr(r))
which looks like this:
array([(611.88243, 9089.5601, 5133., 864.07514, 1715.37476, 765.22777, 1.29111196e+12),
(611.88243, 9089.5601, 5133., 864.07514, 1715.37476, 765.22777, 1.29111311e+12),
(611.88243, 9089.5601, 5133., 864.07514, 1715.37476, 765.22777, 1.29112065e+12)],
dtype=[('A', '<f8'), ('B', '<f8'), ('C', '<f8'), ('D', '<f8'), ('E', '<f8'), ('F', '<f8'), ('timestamp', '<f8')])
You can access a named column like this r['E']
:
array([1715.37476, 1715.37476, 1715.37476])
Note: this answer previously used np.recfromcsv to read the data into a NumPy record array. While there was nothing wrong with that method, structured arrays are generally better than record arrays for speed and compatibility.
As javascript is dynamically typed, rather than using the .length property as above you can simply treat the input value as a boolean:
var input = $.trim($("#spa").val());
if (input) {
// Do Stuff
}
You can also extract the logic out into functions, then by assigning a class and using the each()
method the code is more dynamic if, for example, in the future you wanted to add another input you wouldn't need to change any code.
So rather than hard coding the function call into the input markup, you can give the inputs a class, in this example it's test
, and use:
$(".test").each(function () {
$(this).keyup(function () {
$("#submit").prop("disabled", CheckInputs());
});
});
which would then call the following and return a boolean value to assign to the disabled
property:
function CheckInputs() {
var valid = false;
$(".test").each(function () {
if (valid) { return valid; }
valid = !$.trim($(this).val());
});
return valid;
}
You can see a working example of everything I've mentioned in this JSFiddle.
All of them have there own uses:
If you have an iterable and need to traverse unconditionally to all of them:
for (iterable_type iterable_element : collection)
If you have an iterable but need to conditionally traverse:
for (Iterator iterator = collection.iterator(); iterator.hasNext();)
If data-structure does not implement iterable:
for (int i = 0; i < collection.length; i++)
In my case the problem occurred due to closing my PC while visual studio were remain open, so in result csproj.user file saved empty. Thankfully i have already backup, so i just copied all xml from csproj.user and paste in my affected project csproj.user file ,so it worked perfectly.
This file just contain building device info and some more.
((http?|https|ftp|file)://)?((W|w){3}.)?[a-zA-Z0-9]+\.[a-zA-Z]+
check here:- https://www.freeformatter.com/java-regex-tester.html#ad-output
It sorts out theses entries correctly
char (with a lower-case c) is a numeric type. It already holds the ascii value of the char. Just cast it to an integer to display it as a numeric value rather than a textual value:
System.out.println("char " + ch + " has the following value : " + (int) ch);
Can also do more dynamic inits with fill, e.g.
Array.fill(10){scala.util.Random.nextInt(5)}
==>
Array[Int] = Array(0, 1, 0, 0, 3, 2, 4, 1, 4, 3)
I got the similar requirement and got help from reading few of the above solutions and across other websites, I have came up with below script, Just wanted to share if it might help anyone.
from boto3.session import Session
import os
def sync_s3_folder(access_key_id,secret_access_key,bucket_name,folder,destination_path):
session = Session(aws_access_key_id=access_key_id,aws_secret_access_key=secret_access_key)
s3 = session.resource('s3')
your_bucket = s3.Bucket(bucket_name)
for s3_file in your_bucket.objects.all():
if folder in s3_file.key:
file=os.path.join(destination_path,s3_file.key.replace('/','\\'))
if not os.path.exists(os.path.dirname(file)):
os.makedirs(os.path.dirname(file))
your_bucket.download_file(s3_file.key,file)
sync_s3_folder(access_key_id,secret_access_key,bucket_name,folder,destination_path)
Another valid option is to spread the joins across multiple LINQ clauses, as follows:
public static IEnumerable<Announcementboard> GetSiteContent(string pageName, DateTime date)
{
IEnumerable<Announcementboard> content = null;
IEnumerable<Announcementboard> addMoreContent = null;
try
{
content = from c in DB.Announcementboards
// Can be displayed beginning on this date
where c.Displayondate > date.AddDays(-1)
// Doesn't Expire or Expires at future date
&& (c.Displaythrudate == null || c.Displaythrudate > date)
// Content is NOT draft, and IS published
&& c.Isdraft == "N" && c.Publishedon != null
orderby c.Sortorder ascending, c.Heading ascending
select c;
// Get the content specific to page names
if (!string.IsNullOrEmpty(pageName))
{
addMoreContent = from c in content
join p in DB.Announceonpages on c.Announcementid equals p.Announcementid
join s in DB.Apppagenames on p.Apppagenameid equals s.Apppagenameid
where s.Apppageref.ToLower() == pageName.ToLower()
select c;
}
// Add the specified content using UNION
content = content.Union(addMoreContent);
// Exclude the duplicates using DISTINCT
content = content.Distinct();
return content;
}
catch (MyLovelyException ex)
{
// Add your exception handling here
throw ex;
}
}
Generally, you'd want to use mail
command to send your message using local MTA (that will either deliver it using SMTP to the destination or just forward it into some more powerful SMTP server, for example, at your ISP). If you don't have a local MTA (although it's a bit unusual for a UNIX-like system to omit one), you can either use some minimalistic MTA like ssmtp.
ssmtp
is quite easy to configure. Basically, you'll just need to specify where your provider's SMTP server is:
# The place where the mail goes. The actual machine name is required
# no MX records are consulted. Commonly mailhosts are named mail.domain.com
# The example will fit if you are in domain.com and you mailhub is so named.
mailhub=mail
Another option is to use one of myriads scripts that just connect to SMTP server directly and try to post a message there, such as Smtp-Auth-Email-Script, smtp-cli, SendEmail, etc.
Or in restSharp:
var client = new RestClient("https://example.com/?urlparam=true");
var request = new RestRequest(Method.POST);
request.AddHeader("content-type", "application/x-www-form-urlencoded");
request.AddHeader("cache-control", "no-cache");
request.AddHeader("header1", "headerval");
request.AddParameter("application/x-www-form-urlencoded", "bodykey=bodyval", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
Apparently, gcc doesn't behave like the one described in The C Programming language, where it says that the command cc helloworld.c produces a file called a.out which can be run by typing a.out on the prompt.
A Unix hasn't behaved in that way by default (so you can just write the executable name without ./ at the front) in a long time. It's called a.exe, because else Windows won't execute it, as it gets file types from the extension.
I was fetching a windows-1252 encoded file via cURL and the mb_detect_encoding(curl_exec($ch));
returned UTF-8. Tried utf8_encode(curl_exec($ch));
and the characters were correct.
This should be the most reliable way regardless of the compiler:
m=std::stringstream();
is
compares identity. A string will never be identical to a not-string.
==
is equality. But a string will never be equal to either True
or False
.
You want neither.
path = '/bla/bla/bla'
if path:
print "True"
else:
print "False"
A very simple example:
SET a=Hello
SET b=World
SET c=%a% %b%!
echo %c%
The result should be:
Hello World!
I wrote a simple logger, which can log query with inserted parameters. Installation:
composer require cmyker/doctrine-sql-logger:dev-master
Usage:
$connection = $this->getEntityManager()->getConnection();
$logger = new \Cmyker\DoctrineSqlLogger\Logger($connection);
$connection->getConfiguration()->setSQLLogger($logger);
//some query here
echo $logger->lastQuery;
The SE(JDK) has all the libraries you will ever need to cut your teeth on Java. I recommend the Netbeans IDE as this comes bundled with the SE(JDK) straight from Oracle. Don't forget to set "path" and "classpath" variables especially if you are going to try command line. With a 64 bit system insert the "System Path" e.g. C:\Program Files (x86)\Java\jdk1.7.0 variable before the C:\Windows\system32; to direct the system to your JDK.
hope this helps.
For fpdf to work properly, there cannot be any output at all beside what fpdf generates. For example, this will work:
<?php
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>
While this will not (note the leading space before the opening <?
tag)
<?php
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>
Also, this will not work either (the echo
will break it):
<?php
echo "About to create pdf";
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>
I'm not sure about the drupal side of things, but I know that absolutely zero non-fpdf output is a requirement for fpdf to work.
add ob_start ();
at the top and at the end add ob_end_flush();
<?php
ob_start();
require('fpdf.php');
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
ob_end_flush();
?>
give me an error as below:
FPDF error: Some data has already been output, can't send PDF
to over come this error:
go to fpdf.php
in that,goto line number 996
function Output($name='', $dest='')
after that make changes like this:
function Output($name='', $dest='') {
ob_clean(); //Output PDF to so
Hi do you have a session header on the top of your page. or any includes If you have then try to add this codes on top pf your page it should works fine.
<?
while (ob_get_level())
ob_end_clean();
header("Content-Encoding: None", true);
?>
cheers :-)
In my case i had set:
ini_set('display_errors', 'on');
error_reporting(E_ALL | E_STRICT);
When i made the request to generate the report, some warnings were displayed in the browser (like the usage of deprecated functions).
Turning off
the display_errors
option, the report was generated successfully.
1.redirect return the request to the browser from server,then resend the request to the server from browser.
2.forward send the request to another servlet (servlet to servlet).
The official statement "Due to this restriction, functions and parameters such as autoplay, playVideo(), loadVideoById() won't work in all mobile environments.
Reference: https://developers.google.com/youtube/iframe_api_reference
You can also install json-py from here http://sourceforge.net/projects/json-py/
Method 1:
<script type="text/javascript" language="javascript">
$(document).ready(function(){
$(document).bind("contextmenu",function(e){
return false;
});
});
</script>
Method 2:
<script type="text/javascript" language="javascript">
$(document).ready(function(){
$(document).bind("contextmenu",function(e){
e.preventDefault();
});
});
</script>
public static String getRandomString(int length)
{
String randomStr = UUID.randomUUID().toString();
while(randomStr.length() < length) {
randomStr += UUID.randomUUID().toString();
}
return randomStr.substring(0, length);
}
onChange doesn't fire until you lose focus later. If you want to be really strict with instantaneous changes of all sorts, use:
<input
type = "text"
onchange = "myHandler();"
onkeypress = "this.onchange();"
onpaste = "this.onchange();"
oninput = "this.onchange();"
/>
String input = "";
int inputInteger = 0;
BufferedReader br = new BufferedReader(new InputStreamReader (System.in));
System.out.println("Enter the radious: ");
try {
input = br.readLine();
inputInteger = Integer.parseInt(input);
} catch (NumberFormatException e) {
System.out.println("Please Enter An Integer");
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
float area = (float) (3.14*inputInteger*inputInteger);
System.out.println("Area = "+area);
I like right2clicky's answer, especially in that it doesn't require a Thread to be torn down and a new one created every time the Timer ticks. In addition, it's an easy override to create a class with a timer callback that gets called periodically. That's my normal use case:
class MyClass(RepeatTimer):
def __init__(self, period):
super().__init__(period, self.on_timer)
def on_timer(self):
print("Tick")
if __name__ == "__main__":
mc = MyClass(1)
mc.start()
time.sleep(5)
mc.cancel()
Try this:
$(this).hide("slide", { direction: "left" }, 1000);
$(this).show("slide", { direction: "left" }, 1000);
For limited set of values matplotlib is fine. But when you have lots of values the tooltip starts to overlap over other data points. But with limited space you can't ignore the values. Hence it's better to zoom out or zoom in.
Using plotly
import plotly.express as px
df = px.data.tips()
df = px.data.gapminder().query("year==2007 and continent=='Americas'")
fig = px.scatter(df, x="gdpPercap", y="lifeExp", text="country", log_x=True, size_max=100, color="lifeExp")
fig.update_traces(textposition='top center')
fig.update_layout(title_text='Life Expectency', title_x=0.5)
fig.show()
Screen
If process is running in a screen session you can use screen's log command to log the output of that window to a file:
Switch to the script's window, C-a H to log.
Now you can :
$ tail -f screenlog.2 | grep whatever
From screen's man page:
log [on|off]
Start/stop writing output of the current window to a file "screenlog.n" in the window's default directory, where n is the number of the current window. This filename can be changed with the 'logfile' command. If no parameter is given, the state of logging is toggled. The session log is appended to the previous contents of the file if it already exists. The current contents and the contents of the scrollback history are not included in the session log. Default is 'off'.
I'm sure tmux has something similar as well.
Yes, there are tons of software available to decompile a .apk file.
Recently, I had compiled an ultimate list of 47 best APK decompilers on my website. I arranged them into 4 different sections.
I hope this collection will be helpful to you.
Since you are asking for lambdas, you can use the following syntax with Java 8:
Date maxDate = list.stream().map(u -> u.date).max(Date::compareTo).get();
or, if you have a getter for the date:
Date maxDate = list.stream().map(User::getDate).max(Date::compareTo).get();
The pattern that matches substrings in parentheses having no other (
and )
characters in between (like (xyz 123)
in Text (abc(xyz 123)
) is
\([^()]*\)
Details:
\(
- an opening round bracket (note that in POSIX BRE, (
should be used, see sed
example below)[^()]*
- zero or more (due to the *
Kleene star quantifier) characters other than those defined in the negated character class/POSIX bracket expression, that is, any chars other than (
and )
\)
- a closing round bracket (no escaping in POSIX BRE allowed)Removing code snippets:
string.replace(/\([^()]*\)/g, '')
preg_replace('~\([^()]*\)~', '', $string)
$s =~ s/\([^()]*\)//g
re.sub(r'\([^()]*\)', '', s)
Regex.Replace(str, @"\([^()]*\)", string.Empty)
Regex.Replace(str, "\([^()]*\)", "")
s.replaceAll("\\([^()]*\\)", "")
s.gsub(/\([^()]*\)/, '')
gsub("\\([^()]*\\)", "", x)
string.gsub(s, "%([^()]*%)", "")
sed 's/([^()]*)//g'
regsub -all {\([^()]*\)} $s "" result
std::regex
: std::regex_replace(s, std::regex(R"(\([^()]*\))"), "")
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\([^()]*\\)" options:NSRegularExpressionCaseInsensitive error:&error];
NSString *modifiedString = [regex stringByReplacingMatchesInString:string options:0 range:NSMakeRange(0, [string length]) withTemplate:@""];
s.replacingOccurrences(of: "\\([^()]*\\)", with: "", options: [.regularExpression])
Open VMware Workstation > Edit > Prefrences > Shared VMS > Change port 433 > 4330 > save.
Follow the process Showed in the Following video : https://youtu.be/DYj7qIgwV2M
"comment (cc) and uncomment (cu) code
noremap <silent> cc :s,^\(\s*\)[^# \t]\@=,\1# ,e<CR>:nohls<CR>zvj
noremap <silent> cu :s,^\(\s*\)# \s\@!,\1,e<CR>:nohls<CR>zvj
You can comment/uncomment single or multiple lines with #. To do multiple lines, select the lines then type cc/cu shortcut, or type a number then cc/cu, e.g. 7cc will comment 7 lines from the cursor.
I got the orignal code from the person on What's the most elegant way of commenting / uncommenting blocks of ruby code in Vim? and made some small changes (changed shortcut keys, and added a space after the #).
You can completely destroy a modal without page reloading by this way.
$("#modal").remove();
$('.modal-backdrop').remove();
but it will completely remove modal from your html page. After this modal hide show will not work.
I have viewed all of the answers above but none of them is elegant enough for me. In Pycharm 2017.1.3(in my computer), the easiest way is to open Settings->Tools->Terminal
and check Shell integration
and Activate virtualenv
options.
You can run your file in http-server.
1> Have Node.js installed in your system.
2> In CMD, run the command npm install http-server -g
3> Navigate to the specific path of your file folder in CMD and run the command http-server
4> Go to your browser and type localhost:8080. Your Application should run there.
Thanks:)
printf
is great, but people forget about it.
$ for num in 1 10 100 1000 10000 100000 1000000; do printf "%10s %s\n" $num "foobar"; done
1 foobar
10 foobar
100 foobar
1000 foobar
10000 foobar
100000 foobar
1000000 foobar
$ for((i=0;i<array_size;i++));
do
printf "%10s %10d %10s" stringarray[$i] numberarray[$i] anotherfieldarray[%i]
done
Notice I used %10s
for strings. %s
is the important part. It tells it to use a string. The 10
in the middle says how many columns it is to be. %d
is for numerics (digits).
man 1 printf
for more info.
From the PHP Manual:
Warning This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide. Alternatives to this function include:
mysqli_connect()
PDO::__construct()
use MySQLi
or PDO
<?php
$con = mysqli_connect('localhost', 'username', 'password', 'database');
This next form fixed me the problem.
$('#btnShow').click(function() {_x000D_
$("#basicModal").dialog({_x000D_
modal: true,_x000D_
height: 300,_x000D_
width: 400,_x000D_
create: function() {_x000D_
$(".ui-dialog").find(".ui-dialog-titlebar").css({_x000D_
'background-image': 'none',_x000D_
'background-color': 'white',_x000D_
'border': 'none'_x000D_
});_x000D_
}_x000D_
});_x000D_
});
_x000D_
#basicModal {_x000D_
display: none;_x000D_
}
_x000D_
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>_x000D_
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/themes/smoothness/jquery-ui.css" />_x000D_
<div id="basicModal">_x000D_
Here your HTML content_x000D_
</div>_x000D_
<button id="btnShow">Show me!</button>
_x000D_
We can use replace
to change the values in 'mpg' to NA
that corresponds to cyl==4
.
mtcars %>%
mutate(mpg=replace(mpg, cyl==4, NA)) %>%
as.data.frame()
All the other answers don't seem to explain the use of random.seed(). Here is a simple example (source):
import random
random.seed( 3 )
print "Random number with seed 3 : ", random.random() #will generate a random number
#if you want to use the same random number once again in your program
random.seed( 3 )
random.random() # same random number as before
You can always use strtotime to minus the number of days from the current date:
$users = Users::where('status_id', 'active')
->where( 'created_at', '>', date('Y-m-d', strtotime("-30 days"))
->get();
When a promise is resolved/rejected, it will call its success/error handler:
var promiseB = promiseA.then(function(result) {
// do something with result
});
The then
method also returns a promise: promiseB, which will be resolved/rejected depending on the return value from the success/error handler from promiseA.
There are three possible values that promiseA's success/error handlers can return that will affect promiseB's outcome:
1. Return nothing --> PromiseB is resolved immediately,
and undefined is passed to the success handler of promiseB
2. Return a value --> PromiseB is resolved immediately,
and the value is passed to the success handler of promiseB
3. Return a promise --> When resolved, promiseB will be resolved.
When rejected, promiseB will be rejected. The value passed to
the promiseB's then handler will be the result of the promise
Armed with this understanding, you can make sense of the following:
promiseB = promiseA.then(function(result) {
return result + 1;
});
The then call returns promiseB immediately. When promiseA is resolved, it will pass the result to promiseA's success handler. Since the return value is promiseA's result + 1, the success handler is returning a value (option 2 above), so promiseB will resolve immediately, and promiseB's success handler will be passed promiseA's result + 1.
My answer
/**
* Display form to reply comment
*/
function displayReplyForm(commentId) {
var replyForm = $('#reply-form-' + commentId);
if (replyForm.css('display') == 'block') { // Current display
replyForm.css('display', 'none');
} else { // Hide reply form
replyForm.css('display', 'block');
}
}
You can try overflow
css property.
As of Angular 2.2.3
there is now a forwardRef()
utility function that allows you to inject providers that have not yet been defined.
By not defined, I mean that the dependency injection map doesn't know the identifier. This is what happens during circular dependencies. You can have circular dependencies in Angular that are very difficult to untangle and see.
export class HeaderComponent {
mobileNav: boolean = false;
constructor(@Inject(forwardRef(() => MobileService)) public ms: MobileService) {
console.log(ms);
}
}
Adding @Inject(forwardRef(() => MobileService))
to the parameter of the constructor in the original question's source code will fix the problem.
>>> text=u'abcd'
>>> str(text)
'abcd'
If the string only contains ascii characters.
Scan your workspace .metadata
directory for files called *.launch
. I forget which plugin directory exactly holds these records, but it might even be the most basic org.eclipse.plugins.core
one.
This also works with maven by defining the resources tag. You can name your src folder names whatever you like.
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.java</include>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.java</include>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
</resource>
<resource>
<directory>src/main/generated</directory>
<includes>
<include>**/*.java</include>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
Here's an example of code which uses the UTL_FILE.PUT and UTL_FILE.PUT_LINE calls:
declare
fHandle UTL_FILE.FILE_TYPE;
begin
fHandle := UTL_FILE.FOPEN('my_directory', 'test_file', 'w');
UTL_FILE.PUT(fHandle, 'This is the first line');
UTL_FILE.PUT(fHandle, 'This is the second line');
UTL_FILE.PUT_LINE(fHandle, 'This is the third line');
UTL_FILE.FCLOSE(fHandle);
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('Exception: SQLCODE=' || SQLCODE || ' SQLERRM=' || SQLERRM);
RAISE;
end;
The output from this looks like:
This is the first lineThis is the second lineThis is the third line
Share and enjoy.
UPDATE
(Given the upvotes, I feel there is a need for a complete step-by-step explanation...)
File
->Open Folder...
FOLDERS
sidebar available)View
-> Side Bar
-> Show Side Bar
FOLDERS
-titled Side Bar to navigate to the first file you want to compare.Diff Files...
There should be a new Tab now showing the comparison.
Original short answer:
Note that:
The "Diff files" only appears with the "folders" sidebar (to open a folder: File->Open Folder) , not with "open files" sidebar.
Eclipse has built in JUnit functionality. Open your Run Configuration manager to create a test to run. You can also create JUnit Test Cases/Suites from New->Other.
__func__
is an implicitly declared identifier that expands to a character array variable containing the function name when it is used inside of a function. It was added to C in C99. From C99 §6.4.2.2/1:
The identifier
__func__
is implicitly declared by the translator as if, immediately following the opening brace of each function definition, the declarationstatic const char __func__[] = "function-name";
appeared, where function-name is the name of the lexically-enclosing function. This name is the unadorned name of the function.
Note that it is not a macro and it has no special meaning during preprocessing.
__func__
was added to C++ in C++11, where it is specified as containing "an implementation-de?ned string" (C++11 §8.4.1[dcl.fct.def.general]/8), which is not quite as useful as the specification in C. (The original proposal to add __func__
to C++ was N1642).
__FUNCTION__
is a pre-standard extension that some C compilers support (including gcc and Visual C++); in general, you should use __func__
where it is supported and only use __FUNCTION__
if you are using a compiler that does not support it (for example, Visual C++, which does not support C99 and does not yet support all of C++0x, does not provide __func__
).
__PRETTY_FUNCTION__
is a gcc extension that is mostly the same as __FUNCTION__
, except that for C++ functions it contains the "pretty" name of the function including the signature of the function. Visual C++ has a similar (but not quite identical) extension, __FUNCSIG__
.
For the nonstandard macros, you will want to consult your compiler's documentation. The Visual C++ extensions are included in the MSDN documentation of the C++ compiler's "Predefined Macros". The gcc documentation extensions are described in the gcc documentation page "Function Names as Strings."
The default behavior is:
If the parameter is a primitive type (int
, bool
, double
, ...), Web API tries to get the value from the URI of the HTTP request.
For complex types (your own object, for example: Person
), Web API tries to read the value from the body of the HTTP request.
So, if you have:
...then you don't have to add any attributes (neither [FromBody]
nor [FromUri]
).
But, if you have a primitive type in the body, then you have to add [FromBody]
in front of your primitive type parameter in your WebAPI controller method. (Because, by default, WebAPI is looking for primitive types in the URI of the HTTP request.)
Or, if you have a complex type in your URI, then you must add [FromUri]
. (Because, by default, WebAPI is looking for complex types in the body of the HTTP request by default.)
Primitive types:
public class UsersController : ApiController
{
// api/users
public HttpResponseMessage Post([FromBody]int id)
{
}
// api/users/id
public HttpResponseMessage Post(int id)
{
}
}
Complex types:
public class UsersController : ApiController
{
// api/users
public HttpResponseMessage Post(User user)
{
}
// api/users/user
public HttpResponseMessage Post([FromUri]User user)
{
}
}
This works as long as you send only one parameter in your HTTP request. When sending multiple, you need to create a custom model which has all your parameters like this:
public class MyModel
{
public string MyProperty { get; set; }
public string MyProperty2 { get; set; }
}
[Route("search")]
[HttpPost]
public async Task<dynamic> Search([FromBody] MyModel model)
{
// model.MyProperty;
// model.MyProperty2;
}
From Microsoft's documentation for parameter binding in ASP.NET Web API:
When a parameter has [FromBody], Web API uses the Content-Type header to select a formatter. In this example, the content type is "application/json" and the request body is a raw JSON string (not a JSON object). At most one parameter is allowed to read from the message body.
This should work:
public HttpResponseMessage Post([FromBody] string name) { ... }
This will not work:
// Caution: This won't work! public HttpResponseMessage Post([FromBody] int id, [FromBody] string name) { ... }
The reason for this rule is that the request body might be stored in a non-buffered stream that can only be read once.
Adding this script to my code fixed the dropdown menu.
<script>
$(document).ready(function () {
$('.dropdown-toggle').dropdown();
});
</script>
Although the code isn't perfectly semantic, I think it's more straightforward to have what I call a "clearing div" at the bottom of every container with floats in it. In fact, I've included the following style rule in my reset block for every project:
.clear
{
clear: both;
}
If you're styling for IE6 (god help you), you might want to give this rule a 0px line-height and height as well.
Here a combination of markers and colors from a qualitative colormap in matplotlib
:
import itertools
import numpy as np
from matplotlib import markers
import matplotlib.pyplot as plt
m_styles = markers.MarkerStyle.markers
N = 60
colormap = plt.cm.Dark2.colors # Qualitative colormap
for i, (marker, color) in zip(range(N), itertools.product(m_styles, colormap)):
plt.scatter(*np.random.random(2), color=color, marker=marker, label=i)
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0., ncol=4);
I have some additional needs related to this post that sizeToFit
does not solve. I needed to keep the button centered in it's original location, regardless of the text. I also never want the button to be larger than its original size.
So, I layout the button for its maximum size, save that size in the Controller and use the following method to size the button when the text changes:
+ (void) sizeButtonToText:(UIButton *)button availableSize:(CGSize)availableSize padding:(UIEdgeInsets)padding {
CGRect boundsForText = button.frame;
// Measures string
CGSize stringSize = [button.titleLabel.text sizeWithFont:button.titleLabel.font];
stringSize.width = MIN(stringSize.width + padding.left + padding.right, availableSize.width);
// Center's location of button
boundsForText.origin.x += (boundsForText.size.width - stringSize.width) / 2;
boundsForText.size.width = stringSize.width;
[button setFrame:boundsForText];
}
With strtok(), it can be done in just one line: "if (strtok(s," \t")==NULL)". For example:
#include <stdio.h>
#include <string.h>
int is_whitespace(char *s) {
if (strtok(s," \t")==NULL) {
return 1;
} else {
return 0;
}
}
void demo(void) {
char s1[128];
char s2[128];
strcpy(s1," abc \t ");
strcpy(s2," \t ");
printf("s1 = \"%s\"\n", s1);
printf("s2 = \"%s\"\n", s2);
printf("is_whitespace(s1)=%d\n",is_whitespace(s1));
printf("is_whitespace(s2)=%d\n",is_whitespace(s2));
}
int main() {
char url[63] = {'\0'};
do {
printf("Enter a URL: ");
scanf("%s", url);
printf("url='%s'\n", url);
} while (is_whitespace(url));
return 0;
}
Use "\n":
file.write("My String\n")
See the Python manual for reference.
If you haven't push the deletion yet, you can simply do :
$ git checkout deletedBranchName
That solution from the official wiki:
vzctl set $CTID --netfilter full --save
https://openvz.org/VPN_via_the_TUN/TAP_device#Troubleshooting
UPDATE : check Peter's answer below for a builtin solution :
This is a helper to set a persistent cookie:
import datetime
def set_cookie(response, key, value, days_expire=7):
if days_expire is None:
max_age = 365 * 24 * 60 * 60 # one year
else:
max_age = days_expire * 24 * 60 * 60
expires = datetime.datetime.strftime(
datetime.datetime.utcnow() + datetime.timedelta(seconds=max_age),
"%a, %d-%b-%Y %H:%M:%S GMT",
)
response.set_cookie(
key,
value,
max_age=max_age,
expires=expires,
domain=settings.SESSION_COOKIE_DOMAIN,
secure=settings.SESSION_COOKIE_SECURE or None,
)
Use the following code before sending a response.
def view(request):
response = HttpResponse("hello")
set_cookie(response, 'name', 'jujule')
return response
UPDATE : check Peter's answer below for a builtin solution :
What kind of business data? Trade secrets or just stuff that they don't want people to see but if it got out, it wouldn't be a big deal? If we are talking trade secrets, financial information, customer information and stuff that's generally confidential. Then don't even go down that route.
I'm wondering whether I need to use a secured connection (https) or just the forms authentication is enough.
Use a secure connection all the way.
Do I need to alter the code / Config
Yes. Well may be not. You may want to have an expert do this for you.
Is SSL and https one and the same...
Mostly yes. People usually refer to those things as the same thing.
Do I need to apply with someone to get some license or something.
You probably want to have your certificate signed by a certificate authority. It will cost you or your client a bit of money.
Do I need to make all my pages secured or only the login page...
Use https throughout. Performance is usually not an issue if the site is meant for internal users.
I was searching Internet for answer, but I was not able to get all these points... Any whitepaper or other references would also be helpful...
Start here for some pointers: http://www.owasp.org/index.php/Category:OWASP_Guide_Project
Note that SSL is a minuscule piece of making your web site secure once it is accessible from the internet. It does not prevent most sort of hacking.
This should be the easy way to find the last element:
foreach ( $array as $key => $a ) {
if ( end( array_keys( $array ) ) == $key ) {
echo "Last element";
} else {
echo "Just another element";
}
}
Reference : Link
Facebook does it, when you write on people's walls, but only resizes vertically.
Horizontal resize strikes me as being a mess, due to word-wrap, long lines, and so on, but vertical resize seems to be pretty safe and nice.
None of the Facebook-using-newbies I know have ever mentioned anything about it or been confused. I'd use this as anecdotal evidence to say 'go ahead, implement it'.
Some JavaScript code to do it, using Prototype (because that's what I'm familiar with):
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script src="http://www.google.com/jsapi"></script>
<script language="javascript">
google.load('prototype', '1.6.0.2');
</script>
</head>
<body>
<textarea id="text-area" rows="1" cols="50"></textarea>
<script type="text/javascript" language="javascript">
resizeIt = function() {
var str = $('text-area').value;
var cols = $('text-area').cols;
var linecount = 0;
$A(str.split("\n")).each( function(l) {
linecount += Math.ceil( l.length / cols ); // Take into account long lines
})
$('text-area').rows = linecount + 1;
};
// You could attach to keyUp, etc. if keydown doesn't work
Event.observe('text-area', 'keydown', resizeIt );
resizeIt(); //Initial on load
</script>
</body>
</html>
PS: Obviously this JavaScript code is very naive and not well tested, and you probably don't want to use it on textboxes with novels in them, but you get the general idea.
We had the same repeating problem. It's a disaster. What can you do if cleanup and unlock does not help because there is no existing lock?
.svn
folder in your directory structure. It contains a wc.db
file which is an sql lite file.wc.db
file.I'll describe the way I've stored files, in SQL Server and Oracle. It largely depends on how you are getting the file, in the first place, as to how you will get its contents, and it depends on which database you are using for the content in which you will store it for how you will store it. These are 2 separate database examples with 2 separate methods of getting the file that I used.
SQL Server
Short answer: I used a base64 byte string I converted to a byte[]
and store in a varbinary(max)
field.
Long answer:
Say you're uploading via a website, so you're using an <input id="myFileControl" type="file" />
control, or React DropZone. To get the file, you're doing something like var myFile = document.getElementById("myFileControl")[0];
or myFile = this.state.files[0];
.
From there, I'd get the base64 string using code here: Convert input=file to byte array (use function UploadFile2
).
Then I'd get that string, the file name (myFile.name
) and type (myFile.type
) into a JSON object:
var myJSONObj = {
file: base64string,
name: myFile.name,
type: myFile.type,
}
and post the file to an MVC server backend using XMLHttpRequest, specifying a Content-Type of application/json
: xhr.send(JSON.stringify(myJSONObj);
. You have to build a ViewModel to bind it with:
public class MyModel
{
public string file { get; set; }
public string title { get; set; }
public string type { get; set; }
}
and specify [FromBody]MyModel myModelObj
as the passed in parameter:
[System.Web.Http.HttpPost] // required to spell it out like this if using ApiController, or it will default to System.Mvc.Http.HttpPost
public virtual ActionResult Post([FromBody]MyModel myModelObj)
Then you can add this into that function and save it using Entity Framework:
MY_ATTACHMENT_TABLE_MODEL tblAtchm = new MY_ATTACHMENT_TABLE_MODEL();
tblAtchm.Name = myModelObj.name;
tblAtchm.Type = myModelObj.type;
tblAtchm.File = System.Convert.FromBase64String(myModelObj.file);
EntityFrameworkContextName ef = new EntityFrameworkContextName();
ef.MY_ATTACHMENT_TABLE_MODEL.Add(tblAtchm);
ef.SaveChanges();
tblAtchm.File = System.Convert.FromBase64String(myModelObj.file);
being the operative line.
You would need a model to represent the database table:
public class MY_ATTACHMENT_TABLE_MODEL
{
[Key]
public byte[] File { get; set; } // notice this change
public string Name { get; set; }
public string Type { get; set; }
}
This will save the data into a varbinary(max)
field as a byte[]
. Name
and Type
were nvarchar(250)
and nvarchar(10)
, respectively. You could include size by adding it to your table as an int
column & MY_ATTACHMENT_TABLE_MODEL
as public int Size { get; set;}
, and add in the line tblAtchm.Size = System.Convert.FromBase64String(myModelObj.file).Length;
above.
Oracle
Short answer: Convert it to a byte[]
, assign it to an OracleParameter
, add it to your OracleCommand
, and update your table's BLOB
field using a reference to the parameter's ParameterName
value: :BlobParameter
Long answer:
When I did this for Oracle, I was using an OpenFileDialog
and I retrieved and sent the bytes/file information this way:
byte[] array;
OracleParameter param = new OracleParameter();
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
dlg.Filter = "Image Files (*.jpg, *.jpeg, *.jpe)|*.jpg;*.jpeg;*.jpe|Document Files (*.doc, *.docx, *.pdf)|*.doc;*.docx;*.pdf"
if (dlg.ShowDialog().Value == true)
{
string fileName = dlg.FileName;
using (FileStream fs = File.OpenRead(fileName)
{
array = new byte[fs.Length];
using (BinaryReader binReader = new BinaryReader(fs))
{
array = binReader.ReadBytes((int)fs.Length);
}
// Create an OracleParameter to transmit the Blob
param.OracleDbType = OracleDbType.Blob;
param.ParameterName = "BlobParameter";
param.Value = array; // <-- file bytes are here
}
fileName = fileName.Split('\\')[fileName.Split('\\').Length-1]; // gets last segment of the whole path to just get the name
string fileType = fileName.Split('.')[1];
if (fileType == "doc" || fileType == "docx" || fileType == "pdf")
fileType = "application\\" + fileType;
else
fileType = "image\\" + fileType;
// SQL string containing reference to BlobParameter named above
string sql = String.Format("INSERT INTO YOUR_TABLE (FILE_NAME, FILE_TYPE, FILE_SIZE, FILE_CONTENTS, LAST_MODIFIED) VALUES ('{0}','{1}',{2},:BlobParamerter, SYSDATE)", fileName, fileType, array.Length);
// Do Oracle Update
RunCommand(sql, param);
}
And inside the Oracle update, done with ADO:
public void RunCommand(string sql, OracleParameter param)
{
OracleConnection oraConn = null;
OracleCommand oraCmd = null;
try
{
string connString = GetConnString();
oraConn = OracleConnection(connString);
using (oraConn)
{
if (OraConnection.State == ConnectionState.Open)
OraConnection.Close();
OraConnection.Open();
oraCmd = new OracleCommand(strSQL, oraConnection);
// Add your OracleParameter
if (param != null)
OraCommand.Parameters.Add(param);
// Execute the command
OraCommand.ExecuteNonQuery();
}
}
catch (OracleException err)
{
// handle exception
}
finally
{
OraConnction.Close();
}
}
private string GetConnString()
{
string host = System.Configuration.ConfigurationManager.AppSettings["host"].ToString();
string port = System.Configuration.ConfigurationManager.AppSettings["port"].ToString();
string serviceName = System.Configuration.ConfigurationManager.AppSettings["svcName"].ToString();
string schemaName = System.Configuration.ConfigurationManager.AppSettings["schemaName"].ToString();
string pword = System.Configuration.ConfigurationManager.AppSettings["pword"].ToString(); // hopefully encrypted
if (String.IsNullOrEmpty(host) || String.IsNullOrEmpty(port) || String.IsNullOrEmpty(serviceName) || String.IsNullOrEmpty(schemaName) || String.IsNullOrEmpty(pword))
{
return "Missing Param";
}
else
{
pword = decodePassword(pword); // decrypt here
return String.Format(
"Data Source=(DESCRIPTION =(ADDRESS = ( PROTOCOL = TCP)(HOST = {2})(PORT = {3}))(CONNECT_DATA =(SID = {4})));User Id={0};Password={1};",
user,
pword,
host,
port,
serviceName
);
}
}
And the datatype for the FILE_CONTENTS
column was BLOB
, the FILE_SIZE
was NUMBER(10,0)
, LAST_MODIFIED
was DATE
, and the rest were NVARCHAR2(250)
.
Variable Not Hoisting
let
will not hoist to the entire scope of the block they appear in. By contrast, var
could hoist as below.
{
console.log(cc); // undefined. Caused by hoisting
var cc = 23;
}
{
console.log(bb); // ReferenceError: bb is not defined
let bb = 23;
}
Actually, Per @Bergi, Both var
and let
are hoisted.
Garbage Collection
Block scope of let
is useful relates to closures and garbage collection to reclaim memory. Consider,
function process(data) {
//...
}
var hugeData = { .. };
process(hugeData);
var btn = document.getElementById("mybutton");
btn.addEventListener( "click", function click(evt){
//....
});
The click
handler callback does not need the hugeData
variable at all. Theoretically, after process(..)
runs, the huge data structure hugeData
could be garbage collected. However, it's possible that some JS engine will still have to keep this huge structure, since the click
function has a closure over the entire scope.
However, the block scope can make this huge data structure to garbage collected.
function process(data) {
//...
}
{ // anything declared inside this block can be garbage collected
let hugeData = { .. };
process(hugeData);
}
var btn = document.getElementById("mybutton");
btn.addEventListener( "click", function click(evt){
//....
});
let
loops
let
in the loop can re-binds it to each iteration of the loop, making sure to re-assign it the value from the end of the previous loop iteration. Consider,
// print '5' 5 times
for (var i = 0; i < 5; ++i) {
setTimeout(function () {
console.log(i);
}, 1000);
}
However, replace var
with let
// print 1, 2, 3, 4, 5. now
for (let i = 0; i < 5; ++i) {
setTimeout(function () {
console.log(i);
}, 1000);
}
Because let
create a new lexical environment with those names for a) the initialiser expression b) each iteration (previosly to evaluating the increment expression), more details are here.
This one work for me !! This ngFor so it dynamically anchor tag, You need to wait them render
HTML:
<div #ngForComments *ngFor="let cm of Comments">
<a id="Comment_{{cm.id}}" fragment="Comment_{{cm.id}}" (click)="jumpToId()">{{cm.namae}} Reply</a> Blah Blah
</div>
My ts file:
private fragment: string;
@ViewChildren('ngForComments') AnchorComments: QueryList<any>;
ngOnInit() {
this.route.fragment.subscribe(fragment => { this.fragment = fragment;
});
}
ngAfterViewInit() {
this.AnchorComments.changes.subscribe(t => {
this.ngForRendred();
})
}
ngForRendred() {
this.jumpToId()
}
jumpToId() {
let x = document.querySelector("#" + this.fragment);
console.log(x)
if (x){
x.scrollIntoView();
}
}
Don't forget to import that ViewChildren
, QueryList
etc.. and add some constructor ActivatedRoute
!!
The answer above didn't work for me, this worked:
psql db_development < postgres_db.dump
To use CurrentDb.Execute, your query must be an action query, AND in quotes.
CurrentDb.Execute "queryname"
There's no guarantee that SQL Server won't attempt to perform the CONVERT
to numeric(20,0)
before it runs the filter in the WHERE
clause.
And, even if it did, ISNUMERIC
isn't adequate, since it recognises £
and 1d4
as being numeric, neither of which can be converted to numeric(20,0)
.(*)
Split it into two separate queries, the first of which filters the results and places them in a temp table or table variable, the second of which performs the conversion. (Subqueries and CTEs are inadequate to prevent the optimizer from attempting the conversion before the filter)
For your filter, probably use account_code not like '%[^0-9]%'
instead of ISNUMERIC
.
(*) ISNUMERIC
answers the question that no-one (so far as I'm aware) has ever wanted to ask - "can this string be converted to any of the numeric datatypes - I don't care which?" - when obviously, what most people want to ask is "can this string be converted to x?" where x
is a specific target datatype.
I had 20.8 GB in the C:\Users\ggo\AppData\Local\Android\Sdk\system-images folder (6 android images: - android-10 - android-15 - android-21 - android-23 - android-25 - android-26 ).
I have compressed the C:\Users\ggo\AppData\Local\Android\Sdk\system-images folder.
Now it takes only 4.65 GB.
I did not encountered any problem up to now...
Compression seems to vary from 2/3 to 6, sometimes much more:
Why is 21 the default port for FTP? Or 80 the default for HTTP? It is a convention.
If you set up your file system differently or looking for a different way of setting up a file system and then checking if a file exists in the documents folder heres an another example. also show dynamic checking
for (int i = 0; i < numberHere; ++i){
NSFileManager* fileMgr = [NSFileManager defaultManager];
NSString *documentsDirectory = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
NSString* imageName = [NSString stringWithFormat:@"image-%@.png", i];
NSString* currentFile = [documentsDirectory stringByAppendingPathComponent:imageName];
BOOL fileExists = [fileMgr fileExistsAtPath:currentFile];
if (fileExists == NO){
cout << "DOESNT Exist!" << endl;
} else {
cout << "DOES Exist!" << endl;
}
}
If you are writing portable code, the answer is "you can't tell", the good news is that you don't need to. Your protocol should involve writing the size as (eg) "8 octets, big-endian format" (Ideally with a check that the actual size fits in 8 octets.)
Store both as float, and use unique key words on them.i.em
create table coordinates(
coord_uid counter primary key,
latitude float,
longitude float,
constraint la_long unique(latitude, longitude)
);
Those seem overly complex
def round_down_to():
num = int(datetime.utcnow().replace(second=0, microsecond=0).minute)
return num - (num%10)
If you think logically about how constructors work and what the meaning/usage of a virtual function is in C++ then you will realise that a virtual constructor would be meaningless in C++. Declaring something virtual in C++ means that it can be overridden by a sub-class of the current class, however the constructor is called when the objected is created, at that time you cannot be creating a sub-class of the class, you must be creating the class so there would never be any need to declare a constructor virtual.
And another reason is, the constructors have the same name as its class name and if we declare constructor as virtual, then it should be redefined in its derived class with the same name, but you can not have the same name of two classes. So it is not possible to have a virtual constructor.
As stated above to define a map as constant is not possible. But you can declare a global variable which is a struct that contains a map.
The Initialization would look like this:
var romanNumeralDict = struct {
m map[int]string
}{m: map[int]string {
1000: "M",
900: "CM",
//YOUR VALUES HERE
}}
func main() {
d := 1000
fmt.Printf("Value of Key (%d): %s", d, romanNumeralDict.m[1000])
}
Since you're comparing numbers, you can use an arithmetic expression, which allows for simpler handling of parameters and comparison:
wget -q --tries=10 --timeout=20 --spider http://google.com
if (( $? != 0 )); then
echo "Sorry you are Offline"
exit 1
fi
Notice how instead of -ne
, you can just use !=
. In an arithmetic context, we don't even have to prepend $
to parameters, i.e.,
var_a=1
var_b=2
(( var_a < var_b )) && echo "a is smaller"
works perfectly fine. This doesn't appply to the $?
special parameter, though.
Further, since (( ... ))
evaluates non-zero values to true, i.e., has a return status of 0 for non-zero values and a return status of 1 otherwise, we could shorten to
if (( $? )); then
but this might confuse more people than the keystrokes saved are worth.
The (( ... ))
construct is available in Bash, but not required by the POSIX shell specification (mentioned as possible extension, though).
This all being said, it's better to avoid $?
altogether in my opinion, as in Cole's answer and Steven's answer.
If you have a relatively- (or otherwise-) positioned div you can center something inside it with margin:auto
Vertical centering is a bit tricker, but possible.
write main.c like this -
caution : while linking both main.0 and ClasseAusiliaria.o should be
available to linker.
#include <stdlib.h>
#include <stdio.h>
extern int addizione(int a, int b)
int main(void)
{
int risultato;
risultato = addizione(5,6);
printf("%d\n",risultato);
}
Ok I think I have solves the problem below is a working code
//
package xmlhttp;
import org.jdesktop.http.Response;
import org.jdesktop.http.Session;
import org.jdesktop.http.State;
public class GetXmlHttp{
public static void main(String[] args) {
getResponse();
}
public static void getResponse()
{
final Session session = new Session();
try {
String url="http://192.172.2.23:8080/geoserver/wfs?request=GetFeature&version=1.1.0&outputFormat=GML2&typeName=topp:networkcoverage,topp:tehsil&bbox=73.07846689124875,33.67929015631999,73.07946689124876,33.68029015632,EPSG:4326";
final Response res=session.get(url);
boolean notDone=true;
do
{
System.out.print(session.getState().toString());
if(session.getState()==State.DONE)
{
String xml=res.toString();
System.out.println(xml);
notDone=false;
}
}while(notDone);
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
Ruby's just the same, btw, offering both #length
and #size
as synonyms for the number of items in arrays and hashes (C++ only does it for strings).
Minimalists and people who believe "there ought to be one, and ideally only one, obvious way to do it" (as the Zen of Python recites) will, I guess, mostly agree with your doubts, @Naveen, while fans of Perl's "There's more than one way to do it" (or SQL's syntax with a bazillion optional "noise words" giving umpteen identically equivalent syntactic forms to express one concept) will no doubt be complaining that Ruby, and especially C++, just don't go far enough in offering such synonymical redundancy;-).
In Java, console input is accomplished by reading from System.in. To obtain a character based stream that is attached to the console, wrap System.in in a BufferedReader object. BufferedReader supports a buffered input stream. Its most commonly used constructor is shown here:
BufferedReader(Reader inputReader)
Here, inputReader is the stream that is linked to the instance of BufferedReader that is being created. Reader is an abstract class. One of its concrete subclasses is InputStreamReader, which converts bytes to characters.
To obtain an InputStreamReader object that is linked to System.in, use the following constructor:
InputStreamReader(InputStream inputStream)
Because System.in refers to an object of type InputStream, it can be used for inputStream. Putting it all together, the following line of code creates a BufferedReader that is connected to the keyboard:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
After this statement executes, br is a character-based stream that is linked to the console through System.in.
This is taken from the book Java- The Complete Reference by Herbert Schildt
I wrote a bash program that does all the work of setting up a PR branch for you. It performs forking if needed, syncing with the upstream, setting up upstream remote, etc. and you just need to commit your modifications, push and submit a PR.
Here is how you run it:
github-make-pr-branch ssh your-github-username orig_repo_user orig_repo_name new-feature
You will find the program here and its repository also includes a step-by-step guide to performing the same process manually if you'd like to understand how it works, and also extra information on how to keep your feature branch up-to-date with the upstream master and other useful tidbits.
You have to loop over the input array and add rules for each input as described here: Loop Over Rules
Here is a some code for ya:
$input = Request::all();
$rules = [];
foreach($input['name'] as $key => $val)
{
$rules['name.'.$key] = 'required|distinct|min:3';
}
$rules['amount'] = 'required|integer|min:1';
$rules['description'] = 'required|string';
$validator = Validator::make($input, $rules);
//Now check validation:
if ($validator->fails())
{
/* do something */
}
JavaScript is single threaded and has a synchronous execution model. Single threaded means that one command is being executed at a time. Synchronous means one at a time i.e. one line of code is being executed at time in order the code appears. So in JavaScript one thing is happening at a time.
Execution Context
The JavaScript engine interacts with other engines in the browser. In the JavaScript execution stack there is global context at the bottom and then when we invoke functions the JavaScript engine creates new execution contexts for respective functions. When the called function exits its execution context is popped from the stack, and then next execution context is popped and so on...
For example
function abc()
{
console.log('abc');
}
function xyz()
{
abc()
console.log('xyz');
}
var one = 1;
xyz();
In the above code a global execution context will be created and in this context var one
will be stored and its value will be 1... when the xyz() invocation is called then a new execution context will be created and if we had defined any variable in xyz function those variables would be stored in the execution context of xyz(). In the xyz function we invoke abc() and then the abc() execution context is created and put on the execution stack... Now when abc() finishes its context is popped from stack, then the xyz() context is popped from stack and then global context will be popped...
Now about asynchronous callbacks; asynchronous means more than one at a time.
Just like the execution stack there is the Event Queue. When we want to be notified about some event in the JavaScript engine we can listen to that event, and that event is placed on the queue. For example an Ajax request event, or HTTP request event.
Whenever the execution stack is empty, like shown in above code example, the JavaScript engine periodically looks at the event queue and sees if there is any event to be notified about. For example in the queue there were two events, an ajax request and a HTTP request. It also looks to see if there is a function which needs to be run on that event trigger... So the JavaScript engine is notified about the event and knows the respective function to execute on that event... So the JavaScript engine invokes the handler function, in the example case, e.g. AjaxHandler() will be invoked and like always when a function is invoked its execution context is placed on the execution context and now the function execution finishes and the event ajax request is also removed from the event queue... When AjaxHandler() finishes the execution stack is empty so the engine again looks at the event queue and runs the event handler function of HTTP request which was next in queue. It is important to remember that the event queue is processed only when execution stack is empty.
For example see the code below explaining the execution stack and event queue handling by Javascript engine.
function waitfunction() {
var a = 5000 + new Date().getTime();
while (new Date() < a){}
console.log('waitfunction() context will be popped after this line');
}
function clickHandler() {
console.log('click event handler...');
}
document.addEventListener('click', clickHandler);
waitfunction(); //a new context for this function is created and placed on the execution stack
console.log('global context will be popped after this line');
And
<html>
<head>
</head>
<body>
<script src="program.js"></script>
</body>
</html>
Now run the webpage and click on the page, and see the output on console. The output will be
waitfunction() context will be popped after this line
global context will be emptied after this line
click event handler...
The JavaScript engine is running the code synchronously as explained in the execution context portion, the browser is asynchronously putting things in event queue. So the functions which take a very long time to complete can interrupt event handling. Things happening in a browser like events are handled this way by JavaScript, if there is a listener supposed to run, the engine will run it when the execution stack is empty. And events are processed in the order they happen, so the asynchronous part is about what is happening outside the engine i.e. what should the engine do when those outside events happen.
So JavaScript is always synchronous.
You can use ManualResetEvent. Reset the event before you fire secondary thread and then use the WaitOne() method to block the current thread. You can then have secondary thread set the ManualResetEvent which would cause the main thread to continue. Something like this:
ManualResetEvent oSignalEvent = new ManualResetEvent(false);
void SecondThread(){
//DoStuff
oSignalEvent.Set();
}
void Main(){
//DoStuff
//Call second thread
System.Threading.Thread oSecondThread = new System.Threading.Thread(SecondThread);
oSecondThread.Start();
oSignalEvent.WaitOne(); //This thread will block here until the reset event is sent.
oSignalEvent.Reset();
//Do more stuff
}
I was getting this error because my cpp files was not added in the CMakeLists.txt file
You have to insert your <table>
into a <div>
that it has fixed size, and in <div>
style you have to set overflow: scroll
.
Please run below code may it helps you :)
var str = "this,is,an,example";_x000D_
var strArr = str.split(',');_x000D_
var data = "";_x000D_
for(var i=0; i<strArr.length; i++){_x000D_
data += "Index : "+i+" value : "+strArr[i]+"<br/>";_x000D_
}_x000D_
document.getElementById('print').innerHTML = data;
_x000D_
<div id="print">_x000D_
</div>
_x000D_
This works well for me:
fieldset {_x000D_
text-align:left;_x000D_
border:none_x000D_
}_x000D_
fieldset ol, fieldset ul {_x000D_
padding:0;_x000D_
list-style:none_x000D_
}_x000D_
fieldset li {_x000D_
padding-bottom:1.5em;_x000D_
float:none;_x000D_
clear:left_x000D_
}_x000D_
label {_x000D_
float:left;_x000D_
width:7em;_x000D_
margin-right:1em_x000D_
}_x000D_
fieldset.checkboxes li {_x000D_
clear:both;_x000D_
padding:.75em_x000D_
}_x000D_
fieldset.checkboxes label {_x000D_
margin:0 0 0 1em;_x000D_
width:20em_x000D_
}_x000D_
fieldset.checkboxes input {_x000D_
float:left_x000D_
}
_x000D_
<form>_x000D_
<fieldset class="checkboxes">_x000D_
<ul>_x000D_
<li>_x000D_
<input type="checkbox" name="happy" value="yep" id="happy" />_x000D_
<label for="happy">Happy?</label>_x000D_
</li>_x000D_
<li>_x000D_
<input type="checkbox" name="hungry" value="yep" id="hungry" />_x000D_
<label for="hungry">Hungry?</label>_x000D_
</li>_x000D_
</ul>_x000D_
</fieldset>_x000D_
</form>
_x000D_
If you want to check syntax error for any nginx files, you can use the -c option.
[root@server ~]# sudo nginx -t -c /etc/nginx/my-server.conf
nginx: the configuration file /etc/nginx/my-server.conf syntax is ok
nginx: configuration file /etc/nginx/my-server.conf test is successful
[root@server ~]#
Simple Function :
var myArray = ['January', 'February', 'March'];
function random(array) {
return array[Math.floor(Math.random() * array.length)]
}
random(myArray);
OR
var myArray = ['January', 'February', 'March'];
function random() {
return myArray[Math.floor(Math.random() * myArray.length)]
}
random();
OR
var myArray = ['January', 'February', 'March'];
function random() {
return myArray[Math.floor(Math.random() * myArray.length)]
}
random();
As others have noted, in the instance you are asking about it is the destructor for class Stack
.
But taking your question exactly as it appears in the title:
In c++ what does a tilde “~” before a function name signify?
there is another situation. In any context except immediately before the name of a class (which is the destructor context), ~
is the one's complement (or bitwise not) operator. To be sure it does not come up very often, but you can imagine a case like
if (~getMask()) { ...
which looks similar, but has a very different meaning.
Or a nested List (okay, the OP was for a single column and this is for multiple columns..):
//Base list is a list of fields, ie a data record
//Enclosing list is then a list of those records, ie the Result set
List<List<String>> ResultSet = new List<List<String>>();
using (SqlConnection connection =
new SqlConnection(connectionString))
{
// Create the Command and Parameter objects.
SqlCommand command = new SqlCommand(qString, connection);
// Create and execute the DataReader..
connection.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
var rec = new List<string>();
for (int i = 0; i <= reader.FieldCount-1; i++) //The mathematical formula for reading the next fields must be <=
{
rec.Add(reader.GetString(i));
}
ResultSet.Add(rec);
}
}
Friends I had the same problem because of the different bit version Make sure following point * Your jdk bit 64 or 32 * Your Path for sqljdbc_4.0\enu\auth\x64 or x86 this directory depend on your jdk bit * sqljdbc_auth.dll select this file based on your bit x64 or x86 and put this in system32 folder and it will works for me
There is no inbuilt support for the style change event in jQuery or in java script. But jQuery supports to create custom event and listen to it but every time there is a change, you should have a way to trigger it on yourself. So it will not be a complete solution.
I was having the exact same issue. The problem that I was having is that I hadn't saved the .plt file that I was typing into yet. The fix: I saved the .plt file in the same directory as the data that I was trying to plot and suddenly it worked! If they are in the same directory, you don't even need to specify a path, you can just put in the file name.
Below is exactly what was happening to me, and how I fixed it. The first line shows the problem we were both having. I saved in the second line, and the third line worked!
gnuplot> plot 'c:/Documents and Settings/User/Desktop/data.dat'
warning: Skipping unreadable file c:/Documents and Settings/User/Desktop/data.dat
No data in plot
gnuplot> save 'c:/Documents and Settings/User/Desktop/myfile.plt'
gnuplot> plot 'c:/Documents and Settings/User/Desktop/data.dat'
You can avoid refactoring your code by including the following JavaScript code
jQuery.fn.extend({
live: function (event, callback) {
if (this.selector) {
jQuery(document).on(event, this.selector, callback);
}
return this;
}
});
numpy.random.randint
accepts a third argument (size
) , in which you can specify the size of the output array. You can use this to create your DataFrame
-
df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))
Here - np.random.randint(0,100,size=(100, 4))
- creates an output array of size (100,4)
with random integer elements between [0,100)
.
Demo -
import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))
which produces:
A B C D
0 45 88 44 92
1 62 34 2 86
2 85 65 11 31
3 74 43 42 56
4 90 38 34 93
5 0 94 45 10
6 58 23 23 60
.. .. .. .. ..
"Commercial use" in cases like this is actually just a shorthand to indicate that the product is dual-licensed under both an open source and a traditional paid-for commercial license.
Any "true" open source license will not discriminate against commercial use. (See clause 6 of the Open Source Definition.) However, open source licenses like the GPL contain clauses that are incompatible with most companies' approach to commercial software (since the GPL requires that you make your source code available if you incorporate GPL'ed code into your product).
Duel-licensing is a way to accommodate this and also provides a revenue stream for the company providing the software. For users that don't mind the restrictions of the GPL and don't need support, the product is available under an open source license. For users for whom the GPL's restrictions would be incompatible with their business model, and for users that do need support, a commercial license is available.
You gave the specific example of the Screwturn wiki, which is dual-licensed under the GPL and a commercial license. Under the terms of the GPL (i.e., without getting a "commercial" license), you can do the following:
In other words, there's a lot that you can do without getting a commercial license. This is especially true for web-based software, since people can use web-based software without it being distributed to them. Screwturn's web site even acknowledges this: they state that the commercial license is for "either integrating it in a commercial application, or using it in an enterprise environment where free software is not allowed," not for any use related to commerce.
All of the preceding is merely my understanding and is not intended to be legal advice. Consult your lawyer to be certain.
Polling the last modified file property is a simple yet effective solution though. Just define a class extending my FileChangedWatcher
and implement the onModified()
method:
import java.io.File;
public abstract class FileChangedWatcher
{
private File file;
public FileChangedWatcher(String filePath)
{
file = new File(filePath);
}
public void watch() throws InterruptedException
{
long currentModifiedDate = file.lastModified();
while (true)
{
long newModifiedDate = file.lastModified();
if (newModifiedDate != currentModifiedDate)
{
currentModifiedDate = newModifiedDate;
onModified();
}
Thread.sleep(100);
}
}
public String getFilePath()
{
return file.getAbsolutePath();
}
protected abstract void onModified();
}
round(x[, n]): values are rounded to the closest multiple of 10 to the power minus n. So if n is negative...
def round5(x):
return int(round(x*2, -1)) / 2
Since 10 = 5 * 2, you can use integer division and multiplication with 2, rather than float division and multiplication with 5.0. Not that that matters much, unless you like bit shifting
def round5(x):
return int(round(x << 1, -1)) >> 1
To expand on @Bobby's asnwer above. You can edit your .csproj to use IL-Repack to automatically package all files into a single assembly when you build.
Install-Package ILRepack.MSBuild.Task
Here is a simple sample that merges ExampleAssemblyToMerge.dll into your project output.
<!-- ILRepack -->
<Target Name="AfterBuild" Condition="'$(Configuration)' == 'Release'">
<ItemGroup>
<InputAssemblies Include="$(OutputPath)\$(AssemblyName).exe" />
<InputAssemblies Include="$(OutputPath)\ExampleAssemblyToMerge.dll" />
</ItemGroup>
<ILRepack
Parallel="true"
Internalize="true"
InputAssemblies="@(InputAssemblies)"
TargetKind="Exe"
OutputFile="$(OutputPath)\$(AssemblyName).exe"
/>
</Target>
There's a whole page of the Django documentation devoted to this, well indexed from the contents page.
As that page states, you need to do:
my_obj.categories.add(fragmentCategory.objects.get(id=1))
or
my_obj.categories.create(name='val1')
It's as easy as:
delete object.keyname;
or
delete object["keyname"];
note you can only do this with Numbers and Strings
you could do...
var a, b, c; a = b = c = 0; //but why?
c++;
// c = 1, b = 0, a = 0;
In 9.4.4 using the #>>
operator works for me:
select to_json('test'::text) #>> '{}';
To use with a table column:
select jsoncol #>> '{}' from mytable;
You can do this using with jQuery UI dialog, you can download JQuery ui from here Download JQueryUI
Include these scripts first inside <head>
tag
<link href="css/smoothness/jquery-ui-1.9.0.custom.css" rel="stylesheet">
<script language="javascript" type="text/javascript" src="jquery-1.8.2.js"></script>
<script src="js/jquery-ui-1.9.0.custom.js"></script>
JQuery code
<script language="javascript" type="text/javascript">
$(document).ready(function() {
$('#trigger').click(function(){
$("#dialog").dialog();
});
});
</script>
HTML code within <body>
tag. Use an iframe to load the pdf file inside
<a href="#" id="trigger">this link</a>
<div id="dialog" style="display:none">
<div>
<iframe src="yourpdffile.pdf"></iframe>
</div>
</div>
http://support.microsoft.com/kb/815065
A DLL is a library that contains code and data that can be used by more than one program at the same time. For example, in Windows operating systems, the Comdlg32 DLL performs common dialog box related functions. Therefore, each program can use the functionality that is contained in this DLL to implement an Open dialog box. This helps promote code reuse and efficient memory usage.
By using a DLL, a program can be modularized into separate components. For example, an accounting program may be sold by module. Each module can be loaded into the main program at run time if that module is installed. Because the modules are separate, the load time of the program is faster, and a module is only loaded when that functionality is requested.
Additionally, updates are easier to apply to each module without affecting other parts of the program. For example, you may have a payroll program, and the tax rates change each year. When these changes are isolated to a DLL, you can apply an update without needing to build or install the whole program again.
This works like magic, use it in the CSS file on the div you want to have on the new line:
.div_class {
clear: left;
}
Or declare it in the html:
<div style="clear: left">
<!-- Content... -->
</div>
return value in array
$data = json_decode(file_get_contents('php://input'), true);
This is a simple way of doing something.
@Override
public void onBackPressed() {
// do what you want to do when the "back" button is pressed.
startActivity(new Intent(Activity.this, MainActivity.class));
finish();
}
I think there might be more elaborate ways of going about it, but I like simplicity. For example, I used the template above to make the user sign out of the application AND THEN go back to another activity of my choosing.
To improve Darin's answer, it can be bit shorter:
public class UniqueFileName : ValidationAttribute
{
private readonly NewsService _newsService = new NewsService();
public override bool IsValid(object value)
{
if (value == null) { return false; }
var file = (HttpPostedFile) value;
return _newsService.IsFileNameUnique(file.FileName);
}
}
Model:
[UniqueFileName(ErrorMessage = "This file name is not unique.")]
Do note that an error message is required, otherwise the error will be empty.
The term ‘fixed point’ refers to the corresponding manner in which numbers are represented, with a fixed number of digits after, and sometimes before, the decimal point. With floating-point representation, the placement of the decimal point can ‘float’ relative to the significant digits of the number. For example, a fixed-point representation with a uniform decimal point placement convention can represent the numbers 123.45, 1234.56, 12345.67, etc, whereas a floating-point representation could in addition represent 1.234567, 123456.7, 0.00001234567, 1234567000000000, etc.
Docotic.Pdf library may be used to extract text from PDF files as plain text or as a collection of text chunks with coordinates for each chunk.
Docotic.Pdf can be used to extract images from PDFs, too.
Disclaimer: I work for Bit Miracle.
Simply, change
<textarea rows="15" cols="50" id="aboutDescription"
style="resize: none;"></textarea>
to
<textarea rows="15" cols="50" id="aboutDescription"
style="resize: none;" data-role="none"></textarea>
ie, add:
data-role="none"
Broadly speaking yes return type of overriding method can be different. But it's not straight forward as there are some cases involved in this.
Case 1: If the return type is a primitive data type or void.
Output: If the return type is void or primitive then the data type of parent class method and overriding method should be the same. e.g. if the return type is int, float, string then it should be same
Case 2: If the return type is derived data type:
Output: If the return type of the parent class method is derived type then the return type of the overriding method is the same derived data type of subclass to the derived data type. e.g. Suppose I have a class A, B is a subclass to A, C is a subclass to B and D is a subclass to C; then if the super class is returning type A then the overriding method in subclass can return either A, or B/C/D type i.e. its sub types. This is also called as covariance.
Update:
// use it like this
obj?.a?.lot?.of?.properties
Solution for JavaScript before ECMASCript 2020 or TypeScript older than version 3.7:
A quick workaround is using a try/catch helper function with ES6 arrow function:
function getSafe(fn, defaultVal) {
try {
return fn();
} catch (e) {
return defaultVal;
}
}
// use it like this
console.log(getSafe(() => obj.a.lot.of.properties));
// or add an optional default value
console.log(getSafe(() => obj.a.lot.of.properties, 'nothing'));
_x000D_
[ ]{2,}
SPACE (2 or more)
You could also check that before and after those spaces words follow. (not other whitespace like tabs or new lines)
\w[ ]{2,}\w
the same, but you can also pick (capture) only the spaces for tasks like replacement
\w([ ]{2,})\w
or see that before and after spaces there is anything, not only word characters (except whitespace)
[^\s]([ ]{2,})[^\s]
__name__
changes depending on whether the code in question is run in the global namespace or as part of an imported module.
If the code is not running in the global space, __name__
will be the name of the module. If it is running in global namespace -- for example, if you type it into a console, or run the module as a script using python.exe yourscriptnamehere.py
then __name__
becomes "__main__"
.
You'll see a lot of python code with if __name__ == '__main__'
is used to test whether the code is being run from the global namespace – that allows you to have a module that doubles as a script.
Did you try to do these imports from the console?
classList is available from IE10 onwards, use that if you can.
element.classList.add("something");
element.classList.remove("some-class");
Issue is resolved by:
Bundle bundle = new Bundle();
bundle.putSerializable("data", bigdata);
...
CacheHelper.saveState(bundle,"DATA");
Intent intent = new Intent(mActivity, AActivity.class);
startActivity(intent, bb);// do not put data to intent.
In Activity:
@Override
protected void onCreate(Bundle savedInstanceState) {
Bundle bundle = CacheHelper.getInstance().loadState(Constants.DATA);
if (bundle != null){
Intent intent = getIntent();
intent.putExtras(bundle);
}
getIntent().getExtra(..);
....
}
@Override
protected void onDestroy() {
super.onDestroy();
CacheHelper.clearState("DATA");
}
public class CacheHelper {
public static void saveState(Bundle savedInstanceState, String name) {
Bundle saved = (Bundle) savedInstanceState.clone();
save(name, saved);
}
public Bundle loadState(String name) {
Object object = load(name);
if (object != null) {
Bundle bundle = (Bundle) object;
return bundle;
}
return null;
}
private static void save(String fileName, Bundle object) {
try {
String path = StorageUtils.getFullPath(fileName);
File file = new File(path);
if (file.exists()) {
file.delete();
}
FileOutputStream fos = new FileOutputStream(path, false);
Parcel p = Parcel.obtain(); //creating empty parcel object
object.writeToParcel(p, 0); //saving bundle as parcel
//parcel.writeBundle(bundle);
fos.write(p.marshall()); //writing parcel to file
fos.flush();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private static Bundle load(String fileName) {
try {
String path = StorageUtils.getFullPath(fileName);
FileInputStream fis = new FileInputStream(path);
byte[] array = new byte[(int) fis.getChannel().size()];
fis.read(array, 0, array.length);
Parcel parcel = Parcel.obtain(); //creating empty parcel object
parcel.unmarshall(array, 0, array.length);
parcel.setDataPosition(0);
Bundle out = parcel.readBundle();
out.putAll(out);
fis.close();
parcel.recycle();
return out;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static void clearState(Activity ac) {
String name = ac.getClass().getName();
String path = StorageUtils.getFullPath(name);
File file = new File(path);
if (file.exists()) {
file.delete();
}
}
}
The easiest is to do the following:
String alphabet
with the chars that you want.N = alphabet.length()
java.util.Random
for an int x = nextInt(N)
alphabet.charAt(x)
is a random char from the alphabetHere's an example:
final String alphabet = "0123456789ABCDE";
final int N = alphabet.length();
Random r = new Random();
for (int i = 0; i < 50; i++) {
System.out.print(alphabet.charAt(r.nextInt(N)));
}
It is not possible with the standard query operators - it is Language Integrated Query, not Language Integrated Update. But you could hide your update in extension methods.
public static class UpdateExtension
{
public static IEnumerable<Car> ChangeColorTo(
this IEnumerable<Car> cars, Color color)
{
foreach (Car car in cars)
{
car.Color = color;
yield return car;
}
}
}
Now you can use it as follows.
cars.Where(car => car.Color == Color.Blue).ChangeColorTo(Color.Red);
I always use this code... Use this code
String clientScriptName = "ButtonClickScript";
Type clientScriptType = this.GetType ();
// Get a ClientScriptManager reference from the Page class.
ClientScriptManager clientScript = Page.ClientScript;
// Check to see if the client script is already registered.
if (!clientScript.IsClientScriptBlockRegistered (clientScriptType, clientScriptName))
{
StringBuilder sb = new StringBuilder ();
sb.Append ("<script type='text/javascript'>");
sb.Append ("window.open(' " + url + "')"); //URL = where you want to redirect.
sb.Append ("</script>");
clientScript.RegisterClientScriptBlock (clientScriptType, clientScriptName, sb.ToString ());
}
I had my web server returning:
Content-Type: application\javascript
and couldn't for the life of me figure out what was wrong. Then I realized I had the slash in the wrong direction. It should be:
Content-Type: application/javascript
On top of Emil's awsome answer I'd like to add one more method, for checking if you actually have Internet access as you could have data set to off on your phone.
public static boolean hasInternetAccess(Context c){
TelephonyManager tm = (TelephonyManager) c.getSystemService(Context.TELEPHONY_SERVICE);
if(isConnected(c) && tm.getDataState() == TelephonyManager.DATA_CONNECTED)
return true;
else
return false;
}
Note that this is only for checking if theres a cellular data connection and will return false if you have WiFi connected, as the cellular data is off when WiFi is connected.
You should've kept that DOM ready function
$(function() {
$("#projectKey").change(function() {
alert( $('option:selected', this).text() );
});
});
The document isn't ready if you added the javascript before the elements in the DOM, you have to either use a DOM ready function or add the javascript after the elements, the usual place is right before the </body>
tag
scrollintoview()
increases usabilityInstead of default DOM implementation you can use a plugin that animates movement and doesn't have any unwanted effects. Here's the simplest way of using it with defaults:
$("yourTargetLiSelector").scrollintoview();
Anyway head over to this blog post where you can read all the details and will eventually get you to GitHub source codeof the plugin.
This plugin automatically searches for the closest scrollable ancestor element and scrolls it so that selected element is inside its visible view port. If the element is already in the view port it doesn't do anything of course.
I was looking to do exactly the same thing (RESTful web service), and I stumbled upon this firefox addon, which lets you modify the accept headers (actually, any request headers) for requests. It works perfectly.
Try the following:
boolean isDebuggable = ( 0 != ( getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE ) );
Kotlin:
val isDebuggable = 0 != applicationInfo.flags and ApplicationInfo.FLAG_DEBUGGABLE
It is taken from bundells post from here
Checkout the compiler operation using this
I have added baseUrl in the file for a project like below :
"baseUrl": "src"
It is working fine. So add your base directory for your project.
Yes, you can use GT for free. See the post with explanation. And look at repo on GitHub.
UPD 19.03.2019 Here is a version for browser on GitHub.
I'd suggest you decouple the test method name from your test data set. I would model a DataLoaderFactory class which loads/caches the sets of test data from your resources, and then in your test case cam call some interface method which returns a set of test data for the test case. Having the test data tied to the test method name assumes the test data can only be used once, where in most case i'd suggest that the same test data in uses in multiple tests to verify various aspects of your business logic.
Suppose the dataframe df has 3 columns id1, name1, price1 and you wish to rename them to id2, name2, price2
val list = List("id2", "name2", "price2")
import spark.implicits._
val df2 = df.toDF(list:_*)
df2.columns.foreach(println)
I found this approach useful in many cases.
Solution provided by @Muhd is the best way to do it. But if you are stuck in a situation where changing structure of the page is not an option, use this trick:
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" data-backdrop="false" style="background-color: rgba(0, 0, 0, 0.5);">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"
aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">...</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
The trick in here is data-backdrop="false" style="background-color: rgba(0, 0, 0, 0.5);"
by removing the default backdrop and create a dummy one by setting background color of the dialog itself with some alpha.
Update 1: As pointed out by @Gustyn that clicking on the background does not close the dialog as is expected. So to achieve that you have to add some java script code. Here is some example how you can achieve this.
$('.modal').click(function(event){
$(event.target).modal('hide');
});
var img = new Image();
img.onload = function(){
var height = img.height;
var width = img.width;
// code here to use the dimensions
}
img.src = url;
Yes, you have to interpret the whole binary machine code mess "by hand". Not only that, most of the time you also have to simulate some exotic hardware that doesn't have an equivalent on the target machine.
The simple approach is to interpret the instructions one-by-one. That works well, but it's slow. A faster approach is recompilation - translating the source machine code to target machine code. This is more complicated, as most instructions will not map one-to-one. Instead you will have to make elaborate work-arounds that involve additional code. But in the end it's much faster. Most modern emulators do this.
In python, it's called slicing. Here is an example of python's slice notation:
>>> list1 = ['a','b','c','d','e','f','g','h', 'i', 'j', 'k', 'l']
>>> print list1[:5]
['a', 'b', 'c', 'd', 'e']
>>> print list1[-7:]
['f', 'g', 'h', 'i', 'j', 'k', 'l']
Note how you can slice either positively or negatively. When you use a negative number, it means we slice from right to left.
Expanding on the answer using this:
body {
width: calc(100vw - 17px);
}
One commentor suggested adding left-padding as well to maintain the centering:
body {
padding-left: 17px;
width: calc(100vw - 17px);
}
But then things don't look correct if your content is wider than the viewport. To fix that, you can use media queries, like this:
@media screen and (min-width: 1058px) {
body {
padding-left: 17px;
width: calc(100vw - 17px);
}
}
Where the 1058px = content width + 17 * 2
This lets a horizontal scrollbar handle the x overflow and keeps the centered content centered when the viewport is wide enough to contain your fixed-width content
You can use a Split
:
$text = "test.txt ; 131 136 80 89 119 17 60 123 210 121 188 42 136 200 131 198"
$separator = ";" # you can put many separator like this "; : ,"
$parts = $text.split($separator)
echo $parts[0] # return test.txt
echo $parts[1] # return the part after the separator
As indicated in the question, every sub-command is run in its own shell. This makes writing non-trivial shell scripts a little bit messy -- but it is possible! The solution is to consolidate your script into what make will consider a single sub-command (a single line).
$
by replacing with $$
;
between commands\
set -e
to match make's provision to abort on sub-command failure()
or {}
to emphasize the cohesiveness of a multiple line sequence -- that this is not a typical makefile command sequenceHere's an example inspired by the OP:
mytarget:
{ \
set -e ;\
msg="header:" ;\
for i in $$(seq 1 3) ; do msg="$$msg pre_$${i}_post" ; done ;\
msg="$$msg :footer" ;\
echo msg=$$msg ;\
}
The simplest way I found is to use BitmapDescriptorFactory.defaultMarker() the documentation even has an example of setting the color. From my own code:
MarkerOptions marker = new MarkerOptions()
.title(formatInfo(data))
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
.position(new LatLng(data.getLatitude(), data.getLongitude()))
IF it's still not working for you, I had forgotten to add the fa-ul
class onto the parent (UL) element:
<ul class="fa-ul">
Together with the 2 bits of advice provided already by others:
a) font-family: 'Font Awesome\ 5 Free';
b) font-weight: 900;
solved it for me.
FWIW, the include in my <head>
tags is just:
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.14.0/css/all.min.css" integrity="sha512-1PKOgIY59xJ8Co8+NE6FZ+LOAZKjy+KY8iq0G4B3CyeY6wYHN3yt9PW0XpSriVlkMXe40PTKnXrLnZ9+fkDaog==" crossorigin="anonymous" />
And I am using this with React and Preact. No need for any special React npm installs or components.
As others have said you're subtracting from the numeric values returned from methods like date.getDate()
, you need to reset those values on your date variable. I've created a method below that will do this for you. It creates a date using new Date()
which will initialize with the current date, then sets the date, month, and year according to the values passed in. For example, if you want to go back 6 days then pass in -6 like so var newdate = createDate(-6,0,0)
. If you don't want to set a value pass in a zero (or you could set default values). The method will return the new date for you (tested in Chrome and Firefox).
function createDate(days, months, years) {
var date = new Date();
date.setDate(date.getDate() + days);
date.setMonth(date.getMonth() + months);
date.setFullYear(date.getFullYear() + years);
return date;
}
The dict.items
iterates over the key-value pairs of a dictionary. Therefore for key, value in dictionary.items()
will loop over each pair. This is documented information and you can check it out in the official web page, or even easier, open a python console and type help(dict.items)
. And now, just as an example:
>>> d = {'hello': 34, 'world': 2999}
>>> for key, value in d.items():
... print key, value
...
world 2999
hello 34
The AttributeError
is an exception thrown when an object does not have the attribute you tried to access. The class dict
does not have any predictors
attribute (now you know where to check it :) ), and therefore it complains when you try to access it. As easy as that.
Right now, this is the only way
- name: Ensures {{project_root}}/conf dir exists
file: path={{project_root}}/conf state=directory
- name: Copy file
template:
src: code.conf.j2
dest: "{{project_root}}/conf/code.conf"
Adding system alias for staging deleted files as command rm-all
UNIX
alias rm-all='git rm $(git ls-files --deleted)'
WINDOWS
doskey rm-all=bash -c "git rm $(git ls-files --deleted)"
Note
Windows needs to have bash
installed.
Maybe not related to original code example, but I received the error "Delimiter must not be alphanumeric or backslash" and Googled here. Reason: I mixed order of parameters for preg_match. Pattern was the second parameter and string to match was first. Be careful :)
Just add a 0 or 1 token:
^-?[0-9]\d*(.\d+)?$
You can use VBSedit software to convert your VBS code to .exe file. You can download free version from Internet and installtion vbsedit applilcation on your system and convert the files to exe format.
Vbsedit is a good application for VBscripter's
Replace(@"\""", "")
You have to use double-doublequotes to escape double-quotes within a verbatim string.
Now we have Icon Button to achieve rounded button click and overlay. However background color is not yet available but the same can be achieved by Circle avatar widget as follows:
CircleAvatar(
backgroundColor: const Color(0xffF4F3FA),
child: IconButton(
onPressed: () => FlushbarHelper.createInformation(
message: 'Work in progress...')
.show(context),
icon: Icon(Icons.more_vert),
),
),
Hope this helps some one.
using System.Data;
var myEnumerable = myDataTable.AsEnumerable();
List<MyClass> myClassList =
(from item in myEnumerable
select new MyClass{
MyClassProperty1 = item.Field<string>("DataTableColumnName1"),
MyClassProperty2 = item.Field<string>("DataTableColumnName2")
}).ToList();
DSO here means Dynamic Shared Object; since the error message says it's missing from the command line, I guess you have to add it to the command line.
That is, try adding -lpthread
to your command line.
private DataTable CreateDataTable(IList<T> item)
{
Type type = typeof(T);
var properties = type.GetProperties();
DataTable dataTable = new DataTable();
foreach (PropertyInfo info in properties)
{
dataTable.Columns.Add(new DataColumn(info.Name, Nullable.GetUnderlyingType(info.PropertyType) ?? info.PropertyType));
}
foreach (T entity in item)
{
object[] values = new object[properties.Length];
for (int i = 0; i < properties.Length; i++)
{
values[i] = properties[i].GetValue(entity);
}
dataTable.Rows.Add(values);
}
return dataTable;
}
You may try to develop web apps for iPhone using HTML, JavaScript, CSS. Check the getting started info at Apple's site.
If there is a Content-Disposition: attachment
reponse header, Firefox will ask you to save the file, even if you have JSONView installed to format JSON.
To bypass this problem, I removed the header ("Content-Disposition" : null) with moz-rewrite Firefox addon that allows you to modify request and response headers https://addons.mozilla.org/en-US/firefox/addon/moz-rewrite-js/
An example of JSON file served with this header is the Twitter API (it looks like they added it recently). If you want to try this JSON file, I have a script to access Twitter API in browser: https://gist.github.com/baptx/ffb268758cd4731784e3
The .Elements operation returns a LIST of XElements - but what you really want is a SINGLE element. Add this:
XElement Contacts = (from xml2 in XMLDoc.Elements("Contacts").Elements("Node")
where xml2.Element("ID").Value == variable
select xml2).FirstOrDefault();
This way, you tell LINQ to give you the first (or NULL, if none are there) from that LIST of XElements you're selecting.
Marc
you should do as:
getline(name, sizeofname, '\n');
strtok(name, " ");
This will give you the "joht" in name then to get next token,
temp = strtok(NULL, " ");
temp will get "smith" in it. then you should use string concatination to append the temp at end of name. as:
strcat(name, temp);
(you may also append space first, to obtain a space in between).
With your code, the vue.js
is trying to access the moment()
method from its scope.
Hence you should use a method like this:
methods: {
moment: function () {
return moment();
}
},
If you want to pass a date to the moment.js
, I suggest to use filters:
filters: {
moment: function (date) {
return moment(date).format('MMMM Do YYYY, h:mm:ss a');
}
}
<span>{{ date | moment }}</span>
You need to use the option -f
:
$ grep -f A B
The option -F
does a fixed string search where as -f
is for specifying a file of patterns. You may want both if the file only contains fixed strings and not regexps.
$ grep -Ff A B
You may also want the -w
option for matching whole words only:
$ grep -wFf A B
Read man grep
for a description of all the possible arguments and what they do.
I had the same error message when I switched to guest profile in my emulator. I switched back to owner profile and it worked.
You can do in this way:
int[] numbers= {1,3,4,9,2};
List<int> lst_numbers = new List<int>(numbers);
int required_number = 4;
int i = 0;
foreach (int number in lst_numbers)
{
if(number == required_number)
{
break;
}
i++;
}
lst_numbers.RemoveAt(i);
numbers = lst_numbers.ToArray();
As requested, I have transfered my comment to an answer so people can upvote it:
This works 90% of the time for iOS 13:
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, viewport-fit=cover, user-scalable=no, shrink-to-fit=no" />
and
<meta name="HandheldFriendly" content="true">
You can check out this post on SuperUser.
Word starts page numbering over for each new section by default.
I do it slightly differently than the post above that goes through the ribbon menus, but in both methods you have to go through the document to each section's beginning.
My method:
Format Page Numbers
Continue from Previous Section
radio button under Page numbering
I find this right-click method to be a little faster. Also, usually if I insert the page numbers first before I start making any new sections, this problem doesn't happen in the first place.
If your images are small, consider storing them as base64 in a plain text field.
The reason is that while base64 has an overhead of 33%, with compression that mostly goes away. (See What is the space overhead of Base64 encoding?) Your database will be bigger, but the packets your webserver sends to the client won't be. In html, you can inline base64 in an <img src=""> tag, which can possibly simplify your app because you won't have to serve up the images as binary in a separate browser fetch. Handling images as text also simplifies things when you have to send/receive json, which doesn't handle binary very well.
Yes, I understand you could store the binary in the database and convert it to/from text on the way in and out of the database, but sometimes ORMs make that a hassle. It can be simpler just to treat it as straight text just like all your other fields.
This is definitely the right way to handle thumbnails.
(OP's images are not small, so this is not really an answer to his question.)
Put into a script I like something like that:
#!/bin/bash
set -o xtrace # remove me after debug
TABLE=some_table_name
DB_NAME=prod_database
BASE_DIR=/var/backups/someDir
LOCATION="${BASE_DIR}/myApp_$(date +%Y%m%d_%H%M%S)"
FNAME="${LOCATION}_${DB_NAME}_${TABLE}.sql"
# Create backups directory if not exists
if [[ ! -e $BASE_DIR ]];then
mkdir $BASE_DIR
chown -R postgres:postgres $BASE_DIR
fi
sudo -H -u postgres pg_dump --column-inserts --data-only --table=$TABLE $DB_NAME > $FNAME
sudo gzip $FNAME
Are dictionaries ordered in Python 3.6+?
They are insertion ordered[1]. As of Python 3.6, for the CPython implementation of Python, dictionaries remember the order of items inserted. This is considered an implementation detail in Python 3.6; you need to use OrderedDict
if you want insertion ordering that's guaranteed across other implementations of Python (and other ordered behavior[1]).
As of Python 3.7, this is no longer an implementation detail and instead becomes a language feature. From a python-dev message by GvR:
Make it so. "Dict keeps insertion order" is the ruling. Thanks!
This simply means that you can depend on it. Other implementations of Python must also offer an insertion ordered dictionary if they wish to be a conforming implementation of Python 3.7.
How does the Python
3.6
dictionary implementation perform better[2] than the older one while preserving element order?
Essentially, by keeping two arrays.
The first array, dk_entries
, holds the entries (of type PyDictKeyEntry
) for the dictionary in the order that they were inserted. Preserving order is achieved by this being an append only array where new items are always inserted at the end (insertion order).
The second, dk_indices
, holds the indices for the dk_entries
array (that is, values that indicate the position of the corresponding entry in dk_entries
). This array acts as the hash table. When a key is hashed it leads to one of the indices stored in dk_indices
and the corresponding entry is fetched by indexing dk_entries
. Since only indices are kept, the type of this array depends on the overall size of the dictionary (ranging from type int8_t
(1
byte) to int32_t
/int64_t
(4
/8
bytes) on 32
/64
bit builds)
In the previous implementation, a sparse array of type PyDictKeyEntry
and size dk_size
had to be allocated; unfortunately, it also resulted in a lot of empty space since that array was not allowed to be more than 2/3 * dk_size
full for performance reasons. (and the empty space still had PyDictKeyEntry
size!).
This is not the case now since only the required entries are stored (those that have been inserted) and a sparse array of type intX_t
(X
depending on dict size) 2/3 * dk_size
s full is kept. The empty space changed from type PyDictKeyEntry
to intX_t
.
So, obviously, creating a sparse array of type PyDictKeyEntry
is much more memory demanding than a sparse array for storing int
s.
You can see the full conversation on Python-Dev regarding this feature if interested, it is a good read.
In the original proposal made by Raymond Hettinger, a visualization of the data structures used can be seen which captures the gist of the idea.
For example, the dictionary:
d = {'timmy': 'red', 'barry': 'green', 'guido': 'blue'}
is currently stored as [keyhash, key, value]:
entries = [['--', '--', '--'], [-8522787127447073495, 'barry', 'green'], ['--', '--', '--'], ['--', '--', '--'], ['--', '--', '--'], [-9092791511155847987, 'timmy', 'red'], ['--', '--', '--'], [-6480567542315338377, 'guido', 'blue']]
Instead, the data should be organized as follows:
indices = [None, 1, None, None, None, 0, None, 2] entries = [[-9092791511155847987, 'timmy', 'red'], [-8522787127447073495, 'barry', 'green'], [-6480567542315338377, 'guido', 'blue']]
As you can visually now see, in the original proposal, a lot of space is essentially empty to reduce collisions and make look-ups faster. With the new approach, you reduce the memory required by moving the sparseness where it's really required, in the indices.
[1]: I say "insertion ordered" and not "ordered" since, with the existence of OrderedDict, "ordered" suggests further behavior that the dict
object doesn't provide. OrderedDicts are reversible, provide order sensitive methods and, mainly, provide an order-sensive equality tests (==
, !=
). dict
s currently don't offer any of those behaviors/methods.
[2]: The new dictionary implementations performs better memory wise by being designed more compactly; that's the main benefit here. Speed wise, the difference isn't so drastic, there's places where the new dict might introduce slight regressions (key-lookups, for example) while in others (iteration and resizing come to mind) a performance boost should be present.
Overall, the performance of the dictionary, especially in real-life situations, improves due to the compactness introduced.
Try update your Eclipse with the newest Maven repository as follows:
You can recreate recaptcha , wrap it in a container and only let the checkbox visible. My main problem was that I couldn't take the full width so now it expands to the container width. The only problem is the expiration you can see a flick but as soon it happens I reset it.
See this demo http://codepen.io/alejandrolechuga/pen/YpmOJX
function recaptchaReady () {_x000D_
grecaptcha.render('myrecaptcha', {_x000D_
'sitekey': '6Lc7JBAUAAAAANrF3CJaIjt7T9IEFSmd85Qpc4gj',_x000D_
'expired-callback': function () {_x000D_
grecaptcha.reset();_x000D_
console.log('recatpcha');_x000D_
}_x000D_
});_x000D_
}
_x000D_
.recaptcha-wrapper {_x000D_
height: 70px;_x000D_
overflow: hidden;_x000D_
background-color: #F9F9F9;_x000D_
border-radius: 3px;_x000D_
box-shadow: 0px 0px 4px 1px rgba(0,0,0,0.08);_x000D_
-webkit-box-shadow: 0px 0px 4px 1px rgba(0,0,0,0.08);_x000D_
-moz-box-shadow: 0px 0px 4px 1px rgba(0,0,0,0.08);_x000D_
height: 70px;_x000D_
position: relative;_x000D_
margin-top: 17px;_x000D_
border: 1px solid #d3d3d3;_x000D_
color: #000;_x000D_
}_x000D_
_x000D_
.recaptcha-info {_x000D_
background-size: 32px;_x000D_
height: 32px;_x000D_
margin: 0 13px 0 13px;_x000D_
position: absolute;_x000D_
right: 8px;_x000D_
top: 9px;_x000D_
width: 32px;_x000D_
background-image: url(https://www.gstatic.com/recaptcha/api2/logo_48.png);_x000D_
background-repeat: no-repeat;_x000D_
}_x000D_
.rc-anchor-logo-text {_x000D_
color: #9b9b9b;_x000D_
cursor: default;_x000D_
font-family: Roboto,helvetica,arial,sans-serif;_x000D_
font-size: 10px;_x000D_
font-weight: 400;_x000D_
line-height: 10px;_x000D_
margin-top: 5px;_x000D_
text-align: center;_x000D_
position: absolute;_x000D_
right: 10px;_x000D_
top: 37px;_x000D_
}_x000D_
.rc-anchor-checkbox-label {_x000D_
font-family: Roboto,helvetica,arial,sans-serif;_x000D_
font-size: 14px;_x000D_
font-weight: 400;_x000D_
line-height: 17px;_x000D_
left: 50px;_x000D_
top: 26px;_x000D_
position: absolute;_x000D_
color: black;_x000D_
}_x000D_
.rc-anchor .rc-anchor-normal .rc-anchor-light {_x000D_
border: none;_x000D_
}_x000D_
.rc-anchor-pt {_x000D_
color: #9b9b9b;_x000D_
font-family: Roboto,helvetica,arial,sans-serif;_x000D_
font-size: 8px;_x000D_
font-weight: 400;_x000D_
right: 10px;_x000D_
top: 53px;_x000D_
position: absolute;_x000D_
a:link {_x000D_
color: #9b9b9b;_x000D_
text-decoration: none;_x000D_
}_x000D_
}_x000D_
_x000D_
g-recaptcha {_x000D_
// transform:scale(0.95);_x000D_
// -webkit-transform:scale(0.95);_x000D_
// transform-origin:0 0;_x000D_
// -webkit-transform-origin:0 0;_x000D_
_x000D_
}_x000D_
_x000D_
.g-recaptcha {_x000D_
width: 41px;_x000D_
_x000D_
/* border: 1px solid red; */_x000D_
height: 38px;_x000D_
overflow: hidden;_x000D_
float: left;_x000D_
margin-top: 16px;_x000D_
margin-left: 6px;_x000D_
_x000D_
> div {_x000D_
width: 46px;_x000D_
height: 30px;_x000D_
background-color: #F9F9F9;_x000D_
overflow: hidden;_x000D_
border: 1px solid red;_x000D_
transform: translate3d(-8px, -19px, 0px);_x000D_
}_x000D_
div {_x000D_
border: 0;_x000D_
}_x000D_
}
_x000D_
<script src='https://www.google.com/recaptcha/api.js?onload=recaptchaReady&&render=explicit'></script>_x000D_
_x000D_
<div class="recaptcha-wrapper">_x000D_
<div id="myrecaptcha" class="g-recaptcha"></div>_x000D_
<div class="rc-anchor-checkbox-label">I'm not a Robot.</div>_x000D_
<div class="recaptcha-info"></div>_x000D_
<div class="rc-anchor-logo-text">reCAPTCHA</div>_x000D_
<div class="rc-anchor-pt">_x000D_
<a href="https://www.google.com/intl/en/policies/privacy/" target="_blank">Privacy</a>_x000D_
<span aria-hidden="true" role="presentation"> - </span>_x000D_
<a href="https://www.google.com/intl/en/policies/terms/" target="_blank">Terms</a>_x000D_
</div>_x000D_
</div>
_x000D_