Try running all targets individually to check that all are running correct
run ant target name to run a target individually
e.g. ant build-project
Also the default target you specified is
project basedir="." default="build" name="iControlSilk4J"
This will only execute build-subprojects,build-project and init
function EmailValidation($email)
{
$email = htmlspecialchars(stripslashes(strip_tags($email))); //parse unnecessary characters to prevent exploits
if (eregi('[a-z||0-9]@[a-z||0-9].[a-z]', $email)) {
//checks to make sure the email address is in a valid format
$domain = explode( "@", $email ); //get the domain name
if (@fsockopen ($domain[1],80,$errno,$errstr,3)) {
//if the connection can be established, the email address is probably valid
echo "Domain Name is valid ";
return true;
} else {
echo "Con not a email domian";
return false; //if a connection cannot be established return false
}
return false; //if email address is an invalid format return false
}
}
Use another text editor
env EDITOR=nano crontab -e
or
env EDITOR=code crontab -e
Spring Boot already has support for profile based properties.
Simply add an application-[profile].properties
file and specify the profiles to use using the spring.profiles.active
property.
-Dspring.profiles.active=local
This will load the application.properties
and the application-local.properties
with the latter overriding properties from the first.
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:state_pressed="true" android:drawable="@drawable/YOUR DRAWABLE XML" />
<item android:drawable="@drawable/YOUR DRAWABLE XML" />
</selector>
You can also use a href attribute and send a get with the value appended for each button. But the form wouldn't be required then
href="/SubmitForm?action=delete"
href="/SubmitForm?action=save"
For me I was working under Ubuntu
The error disappeared if I use sudo with ng
sudo ng build
sudo ng serve
If you are using an old version of FFMPEG and you cant upgrade you can do the following:
ffmpeg -i PATH/VIDEO_FILE_NAME.mp4 -i PATH/AUDIO_FILE_NAME.mp3 -vcodec copy -shortest DESTINATION_PATH/NEW_VIDEO_FILE_NAME.mp4
Notice that I used -vcodec
The code you are talking about sounds like ServiceLoader
, which was introduced in Java 6 to support a feature that has been defined since Java 1.3 or earlier. For performance reasons, this is the recommended approach to find interface implementations at runtime; if you need support for this in an older version of Java, I hope that you'll find my implementation helpful.
There are a couple of implementations of this in earlier versions of Java, but in the Sun packages, not in the core API (I think there are some classes internal to ImageIO that do this). As the code is simple, I'd recommend providing your own implementation rather than relying on non-standard Sun code which is subject to change.
You could also send your testers the apk that is signed with your debug key. You can find that in the bin folder of your project after building in debug mode.
List<int> list = new List<int> { 5, 7, 3 };
list.Sort((x,y)=> y.CompareTo(x));
list.ForEach(action => { Console.Write(action + " "); });
I still prefer using dc, which is an RPN calculator, so quick session to divide 67 by 18 with 4 digits precision would look like
>dc
4k
67
18/p
3.7222
q
>
Obviously, much more available: man dc
There isn't any EditorFor
override that lets you pass in an anonymous object whose properties would somehow get added as attributes on some tag, especially for the built-in editor templates. You would need to write your own custom editor template and pass the value you want as additional viewdata.
You have to manually filter result based on change of input each time by keeping listener over input
event. While doing manually filtering make sure you should maintain two copy of variable, one would be original collection copy & second would be filteredCollection
copy. The advantage for going this way could save your couple of unnecessary filtering on change detection cycle. You may see a more code, but this would be more performance friendly.
Markup - HTML Template
<md-input #myInput placeholder="Item name..." [(ngModel)]="name" (input)="filterItem(myInput.value)"></md-input>
<div *ngFor="let item of filteredItems">
{{item.name}}
</div>
Code
assignCopy(){
this.filteredItems = Object.assign([], this.items);
}
filterItem(value){
if(!value){
this.assignCopy();
} // when nothing has typed
this.filteredItems = Object.assign([], this.items).filter(
item => item.name.toLowerCase().indexOf(value.toLowerCase()) > -1
)
}
this.assignCopy();//when you fetch collection from server.
My solution to this (which hasn't caused any performance issues):
Array.prototype.remove = function(from, to) { var rest = this.slice((to || from) + 1 || this.length); this.length = from < 0 ? this.length + from : from; return this.push.apply(this, rest); };
I'm using it in all of my projects and credits go to John Resig John Resig's Site
$scope.items.forEach(function(element, index, array){ if(element.name === 'ted'){ $scope.items.remove(index); } });
At the end the $digest will be fired in angularjs and my UI is updated immediately without any recognizable lag.
This is not an answer to the original question "What are the differences between .gitignore and .gitkeep?" but posting here to help people to keep track of empty dir in a simple fashion. To track empty directory and knowling that .gitkeep
is not official part of git,
just add a empty (with no content) .gitignore
file in it.
So for e.g. if you have /project/content/posts
and sometimes posts
directory might be empty then create empty file /project/content/posts/.gitignore
with no content to track that directory and its future files in git.
If Symfony 4 or 5, juste use this code (Where name is the name of your field):
$request->request->get('name');
Going down your list:
Utf32String
class as part of my MiscUtil library, should you ever want it. (It's not been very thoroughly tested, mind you.)There's more on my Unicode page and tips for debugging Unicode problems.
The other big resource of code is unicode.org which contains more information than you'll ever be able to work your way through - possibly the most useful bit is the code charts.
I would use the following if statement because it is easier to read (and modify in the future)
if(!isset($_GET) || !is_array($_GET) || count($_GET)==0) {
// empty, let's make sure it's an empty array for further reference
$_GET=array();
// or unset it
// or set it to null
// etc...
}
The problem is most likely because you config custom UITableViewCell
in storyboard but you do not use storyboard to instantiate your UITableViewController
which uses this UITableViewCell
. For example, in MainStoryboard, you have a UITableViewController
subclass called MyTableViewController
and have a custom dynamic UITableViewCell
called MyTableViewCell
with identifier id "MyCell".
If you create your custom UITableViewController
like this:
MyTableViewController *myTableViewController = [[MyTableViewController alloc] init];
It will not automatically register your custom tableviewcell for you. You have to manually register it.
But if you use storyboard to instantiate MyTableViewController
, like this:
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
MyTableViewController *myTableViewController = [storyboard instantiateViewControllerWithIdentifier:@"MyTableViewController"];
Nice thing happens! UITableViewController
will automatically register your custom tableview cell that you define in storyboard for you.
In your delegate method "cellForRowAtIndexPath", you can create you table view cell like this :
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"MyCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
//Configure your cell here ...
return cell;
}
dequeueReusableCellWithIdentifier will automatically create new cell for you if there is not reusable cell available in the recycling queue.
Then you are done!
I used the following online tool: https://www.get-metadata.com It allows to upload a file and analyze it and then shows all its metadata.
The way you have used the HTML syntax is problematic.
This is how the syntax should be
style="property1:value1;property2:value2"
In your case, this will be the way to do
<h2 style="text-align :center; font-family :tahoma" >TITLE</h2>
A further example would be as follows
<div class ="row">
<button type="button" style= "margin-top : 20px; border-radius: 15px"
class="btn btn-primary">View Full Profile</button>
</div>
I think that this is the best solution if you want to generalize your object cloning algorithm.
It can be used with or without jQuery, although I recommend leaving jQuery's extend method out if you want you the cloned object to have the same "class" as the original one.
function clone(obj){
if(typeof(obj) == 'function')//it's a simple function
return obj;
//of it's not an object (but could be an array...even if in javascript arrays are objects)
if(typeof(obj) != 'object' || obj.constructor.toString().indexOf('Array')!=-1)
if(JSON != undefined)//if we have the JSON obj
try{
return JSON.parse(JSON.stringify(obj));
}catch(err){
return JSON.parse('"'+JSON.stringify(obj)+'"');
}
else
try{
return eval(uneval(obj));
}catch(err){
return eval('"'+uneval(obj)+'"');
}
// I used to rely on jQuery for this, but the "extend" function returns
//an object similar to the one cloned,
//but that was not an instance (instanceof) of the cloned class
/*
if(jQuery != undefined)//if we use the jQuery plugin
return jQuery.extend(true,{},obj);
else//we recursivley clone the object
*/
return (function _clone(obj){
if(obj == null || typeof(obj) != 'object')
return obj;
function temp () {};
temp.prototype = obj;
var F = new temp;
for(var key in obj)
F[key] = clone(obj[key]);
return F;
})(obj);
}
Type-safe means that programmatically, the type of data for a variable, return value, or argument must fit within a certain criteria.
In practice, this means that 7 (an integer type) is different from "7" (a quoted character of string type).
PHP, Javascript and other dynamic scripting languages are usually weakly-typed, in that they will convert a (string) "7" to an (integer) 7 if you try to add "7" + 3, although sometimes you have to do this explicitly (and Javascript uses the "+" character for concatenation).
C/C++/Java will not understand that, or will concatenate the result into "73" instead. Type-safety prevents these types of bugs in code by making the type requirement explicit.
Type-safety is very useful. The solution to the above "7" + 3 would be to type cast (int) "7" + 3 (equals 10).
no need for the padding or the corners.
here's a sample:
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval" >
<gradient android:startColor="#FFFF0000" android:endColor="#80FF00FF"
android:angle="270"/>
</shape>
based on :
I store my non-Github repo's on Dropbox. One caveat I ran into was syncing after a reinstall. Dropbox will download the smallest files first before moving to the larger ones. Not an issue if you start at night and come back after the weekend :-)
My thread - http://forums.dropbox.com/topic.php?id=29984&replies=6
Depending on how you want to work your script you have two options. If you want the commands to block and not do anything while it is executing, you can just use subprocess.call
.
#start and block until done
subprocess.call([data["om_points"], ">", diz['d']+"/points.xml"])
If you want to do things while it is executing or feed things into stdin
, you can use communicate
after the popen
call.
#start and process things, then wait
p = subprocess.Popen([data["om_points"], ">", diz['d']+"/points.xml"])
print "Happens while running"
p.communicate() #now wait plus that you can send commands to process
As stated in the documentation, wait
can deadlock, so communicate is advisable.
Since you are looking for adding space between elements you may need something as simple as a margin-left or padding-left. Here are examples of both http://jsfiddle.net/BGHqn/3/
This will add 10 pixels to the left of the paragraph element
p {
margin-left: 10px;
}
or if you just want some padding within your paragraph element
p {
padding-left: 10px;
}
You can change default options by using Chart.defaults.global
in your javascript file. So you want to change legend and tooltip options.
Chart.defaults.global.legend.display = false;
Chart.defaults.global.tooltips.enabled = false;
Here is a working fiddler.
css is enough :
width : desired_width;
height: auto;/*to preserve the aspect ratio of the image*/
test -z
returns true if the parameter is empty (see man sh
or man test
).
in my case I had to add
target 'SomeTargetTests' do
inherit! :search_paths
end
to my podfile and then delete the /Pods directory and run `pod install`
(Xcode 10.1)
//Do it like---
function dragStart(this_,event) {
var row=$(this_).attr('whatever');
event.dataTransfer.setData("Text", row);
}
Fundamentally you hadn't declare location which is what nginx uses to bind URL with resources.
server {
listen 80;
server_name localhost;
access_log logs/localhost.access.log main;
location / {
root /var/www/board/public;
index index.html index.htm index.php;
}
}
You can use the patch function for setting defaults with some of the values in your form group.
component.html
<form [formGroup]="countryForm">
<select id="country" formControlName="country">
<option *ngFor="let c of countries" [ngValue]="c">{{ c }}</option>
</select>
</form>
component.ts
import { FormControl, FormGroup, Validators } from '@angular/forms';
export class Component implements OnInit{
countries: string[] = ['USA', 'UK', 'Canada'];
default: string = 'UK';
countryForm: FormGroup;
constructor() {
this.countryForm.controls['country'].setValue(this.default, {onlySelf: true});
}
}
ngOnInit() {
this.countryForm = new FormGroup({
'country': new FormControl(null)
});
this.countryForm.patchValue({
'country': default
});
}
You need to add an additional parameter:
$http.get(url).then(
function(response) {
console.log('get',response)
},
function(data) {
// Handle error here
})
I'd recommend the DIY way which, combined with a good hashCode() and equals() method should be easy to proof in a unit test.
The following command will create a root directory "." and put all the files from the specified directory into it.
tar -cjf site1.tar.bz2 -C /var/www/site1 .
If you want to put all files in root of the tar file, @chinthaka is right. Just cd in to the directory and do:
tar -cjf target_path/file.tar.gz *
This will put all the files in the cwd to the tar file as root files.
I had the same problem, and I solved it by installing :
NB : 64 bit installation was enough, I had to uninstall / reinstall Wamp after that
In PowerShell Core v6 (works on macOS, Linux and Windows):
[Environment]::MachineName
When you do the second one, you're making a new arraylist, you're not trying to pretend the other list is an arraylist.
I mean, what if the original list is implemented as a linkedlist, or some custom list? You won't know. The second approach is preferred if you really need to make an arraylist from the result. But you can just leave it as a list, that's one of the best advantages of using Interfaces!
Your code sets the timeout to 1000 seconds. For milliseconds, use CURLOPT_TIMEOUT_MS
.
Hi recently looked into this and had issues referencing the named table (list object) within excel
if you place a suffix '$' on the table name all is well in the world
Sub testSQL()
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
' Declare variables
strFile = ThisWorkbook.FullName
' construct connection string
strCon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & strFile _
& ";Extended Properties=""Excel 12.0;HDR=Yes;IMEX=1"";"
' create connection and recordset objects
Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
' open connection
cn.Open strCon
' construct SQL query
strSQL = "SELECT * FROM [TableName$] where [ColumnHeader] = 'wibble';"
' execute SQL query
rs.Open strSQL, cn
Debug.Print rs.GetString
' close connection
rs.Close
cn.Close
Set rs = Nothing
Set cn = Nothing
End Sub
I had the same error but i resolved it, it was a syntax error in the AngularJS provider
The problem I was having, is that I kept adding a semi-colon ;
at the end of the url()
value, which prevented the code from working.
? NOT WORKING CODE:
$('#image_element').css('background-image', 'url(http://example.com/img.jpg);');
? WORKING CODE:
$('#image_element').css('background-image', 'url(http://example.com/img.jpg)');
Notice the omitted semi-colon ;
at the end in the working code. I simply didn't know the correct syntax, and it's really hard to notice it. Hopefully this helps someone else in the same boat.
Go to MINGW32 terminal put this Command : git branch --set-upstream-to=origin/(branch Name)
If there are too many cookies cached, it breaks the server (the size of a request header is too big!). Clearing the cookies can fix this issue as well.
You can do it using named-entity recognition (NER). It's fairly simple and there are out-of-the-shelf tools out there to do it, such as spaCy.
NER is an NLP task where a neural network (or other method) is trained to detect certain entities, such as names, places, dates and organizations.
Example:
Sponge Bob went to South beach, he payed a ticket of $200!
I know, Michael is a good person, he goes to McDonalds, but donates to charity at St. Louis street.
Returns:
Just be aware that this is not 100%!
Here are a little snippet for you to try out:
import spacy
phrases = ['Sponge Bob went to South beach, he payed a ticket of $200!', 'I know, Michael is a good person, he goes to McDonalds, but donates to charity at St. Louis street.']
nlp = spacy.load('en')
for phrase in phrases:
doc = nlp(phrase)
replaced = ""
for token in doc:
if token in doc.ents:
replaced+="XXXX "
else:
replaced+=token.text+" "
Read more here: https://spacy.io/usage/linguistic-features#named-entities
You could, instead of replacing with XXXX, replace based on the entity type, like:
if ent.label_ == "PERSON":
replaced += "<PERSON> "
Then:
import re, random
personames = ["Jack", "Mike", "Bob", "Dylan"]
phrase = re.replace("<PERSON>", random.choice(personames), phrase)
This is taken from the Python docs:
Identifiers (also referred to as names) are described by the following lexical definitions:
identifier ::= (letter|"_") (letter | digit | "_")*
letter ::= lowercase | uppercase
lowercase ::= "a"..."z"
uppercase ::= "A"..."Z"
digit ::= "0"..."9"
Identifiers are unlimited in length. Case is significant.
That should explain how to name your variables.
I had the same problem today. If after you delete all of the connections, the connection properties still live on. I clicked on properties, deleted the name by selecting the name window and deleting it.
A warning came up to verify I really wanted to do it. After selecting yes, it got rid of the connection. Save the workbook.
I am a hack at Excel but this seemed to work.
There is no way in PostgreSQL to deconstruct a scalar JSON object. Thus, as you point out,
select length(to_json('Some "text"'::TEXT) ::TEXT);
is 15,
The trick is to convert the JSON into an array of one JSON element, then extract that element using ->>
.
select length( array_to_json(array[to_json('Some "text"'::TEXT)])->>0 );
will return 11.
Unfortunately, none of the ten answers posted so far are quite right.
If you are measuring elapsed time, and you want it to be correct, you must use System.nanoTime()
. You cannot use System.currentTimeMillis()
, unless you don't mind your result being wrong.
The purpose of nanoTime
is to measure elapsed time, and the purpose of currentTimeMillis
is to measure wall-clock time. You can't use the one for the other purpose. The reason is that no computer's clock is perfect; it always drifts and occasionally needs to be corrected. This correction might either happen manually, or in the case of most machines, there's a process that runs and continually issues small corrections to the system clock ("wall clock"). These tend to happen often. Another such correction happens whenever there is a leap second.
Since nanoTime
's purpose is to measure elapsed time, it is unaffected by any of these small corrections. It is what you want to use. Any timings currently underway with currentTimeMillis
will be off -- possibly even negative.
You may say, "this doesn't sound like it would ever really matter that much," to which I say, maybe not, but overall, isn't correct code just better than incorrect code? Besides, nanoTime
is shorter to type anyway.
Previously posted disclaimers about nanoTime
usually having only microsecond precision are valid. Also it can take more than a whole microsecond to invoke, depending on circumstances (as can the other one), so don't expect to time very very small intervals correctly.
A one-liner to extract the certificate from a remote server in PEM format, this time using sed
:
openssl s_client -connect www.google.com:443 2>/dev/null </dev/null | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p'
An alternative would to use the jdbc.drivers System property to specify your required drivers(s) on the command line when you start the JVM.
It could be any one of the parameter, not just the file name or alias - for me it was the Key Password.
If we're going to mention regular expressions, we might as well mention the switch
statement.
var expr = 'Papayas';_x000D_
switch (expr) {_x000D_
case 'Oranges':_x000D_
console.log('Oranges are $0.59 a pound.');_x000D_
break;_x000D_
case 'Mangoes':_x000D_
case 'Papayas': // Mangoes or papayas_x000D_
console.log('Mangoes and papayas are $2.79 a pound.');_x000D_
// expected output: "Mangoes and papayas are $2.79 a pound."_x000D_
break;_x000D_
default:_x000D_
console.log('Sorry, we are out of ' + expr + '.');_x000D_
}
_x000D_
I suggest using ES5 array methods:
["myCircle1","myCircle2","myCircle3","myCircle4"] // Array of IDs
.map(document.getElementById, document) // Array of elements
.forEach(doStuff);
Then doStuff
will be called once for each element, and will receive 3 arguments: the element, the index of the element inside the array of elements, and the array of elements.
Finally I got solution for this, check my App module file :
import { BrowserModule } from '@angular/platform-browser';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MaterialModule } from '@angular/material';
import 'hammerjs';
import { ChartModule } from 'angular2-highcharts';
import * as highcharts from 'highcharts';
import { HighchartsStatic } from 'angular2-highcharts/dist/HighchartsService';
import { AppRouting } from './app.routing';
import { AppComponent } from './app.component';
declare var require: any;
export function highchartsFactory() {
const hc = require('highcharts');
const dd = require('highcharts/modules/drilldown');
dd(hc);
return hc;
}
@NgModule({
declarations: [
AppComponent,
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
AppRouting,
BrowserAnimationsModule,
MaterialModule,
ChartModule
],
providers: [{
provide: HighchartsStatic,
useFactory: highchartsFactory
}],
bootstrap: [AppComponent]
})
export class AppModule { }
Notice declare var require: any;
in the above code.
You get one for free, called ROWID. This is in every SQLite table whether you ask for it or not.
If you include a column of type INTEGER PRIMARY KEY, that column points at (is an alias for) the automatic ROWID column.
ROWID (by whatever name you call it) is assigned a value whenever you INSERT a row, as you would expect. If you explicitly assign a non-NULL value on INSERT, it will get that specified value instead of the auto-increment. If you explicitly assign a value of NULL on INSERT, it will get the next auto-increment value.
Also, you should try to avoid:
INSERT INTO people VALUES ("John", "Smith");
and use
INSERT INTO people (first_name, last_name) VALUES ("John", "Smith");
instead. The first version is very fragile — if you ever add, move, or delete columns in your table definition the INSERT will either fail or produce incorrect data (with the values in the wrong columns).
In my case, the program was running fine, but after one day, I just ran into this problem without doing anything...
The solution was to manually add 'Main' as the Entry Point (before editing, the area was empty):
We faced the same problem:
ORA-29913: error in executing ODCIEXTTABLEOPEN callout
ORA-29400: data cartridge error error opening file /fs01/app/rms01/external/logs/SH_EXT_TAB_VGAG_DELIV_SCHED.log
In our case we had a RAC with 2 nodes. After giving write permission on the log directory, on both sides, everything worked fine.
I use the ArrayDebugView add-in for Visual Studio (http://arraydebugview.sourceforge.net/).
It seems to be a long dead project (but one I'm looking at continuing myself) but the add-in still works beautifully for me in VS2010 for both C++ and C#.
It has a few quirks (tab order, modal dialog, no close button) but the ability to plot the contents of an array in a graph more than make up for it.
Edit July 2014: I have finally built a new Visual Studio extension to replace ArrayebugView's functionality. It is available on the VIsual Studio Gallery, search for ArrayPlotter or go to http://visualstudiogallery.msdn.microsoft.com/2fde2c3c-5b83-4d2a-a71e-5fdd83ce6b96?SRC=Home
It allows servlets to have multiple servlet mappings:
<servlet>
<servlet-name>Servlet1</servlet-name>
<servlet-path>foo.Servlet</servlet-path>
</servlet>
<servlet-mapping>
<servlet-name>Servlet1</servlet-name>
<url-pattern>/enroll</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Servlet1</servlet-name>
<url-pattern>/pay</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Servlet1</servlet-name>
<url-pattern>/bill</url-pattern>
</servlet-mapping>
It allows filters to be mapped on the particular servlet:
<filter-mapping>
<filter-name>Filter1</filter-name>
<servlet-name>Servlet1</servlet-name>
</filter-mapping>
Your proposal would support neither of them. Note that the web.xml
is read and parsed only once during application's startup, not on every HTTP request as you seem to think.
Since Servlet 3.0, there's the @WebServlet
annotation which minimizes this boilerplate:
@WebServlet("/enroll")
public class Servlet1 extends HttpServlet {
Setting an Initial Catalog allows you to set the database that queries run on that connection will use by default. If you do not set this for a connection to a server in which multiple databases are present, in many cases you will be required to have a USE statement in every query in order to explicitly declare which database you are trying to run the query on. The Initial Catalog setting is a good way of explicitly declaring a default database.
Unfortunately, strptime()
can only handle the timezone configured by your OS, and then only as a time offset, really. From the documentation:
Support for the
%Z
directive is based on the values contained intzname
and whetherdaylight
is true. Because of this, it is platform-specific except for recognizing UTC and GMT which are always known (and are considered to be non-daylight savings timezones).
strftime()
doesn't officially support %z
.
You are stuck with python-dateutil
to support timezone parsing, I am afraid.
I have a struct KeyValuePairSerializable
:
[Serializable]
public struct KeyValuePairSerializable<K, V>
{
public KeyValuePairSerializable(KeyValuePair<K, V> pair)
{
Key = pair.Key;
Value = pair.Value;
}
[XmlAttribute]
public K Key { get; set; }
[XmlText]
public V Value { get; set; }
public override string ToString()
{
return "[" + StringHelper.ToString(Key, "") + ", " + StringHelper.ToString(Value, "") + "]";
}
}
Then, the XML serialization of a Dictionary
property is by:
[XmlIgnore]
public Dictionary<string, string> Parameters { get; set; }
[XmlArray("Parameters")]
[XmlArrayItem("Pair")]
[DebuggerBrowsable(DebuggerBrowsableState.Never)] // not necessary
public KeyValuePairSerializable<string, string>[] ParametersXml
{
get
{
return Parameters?.Select(p => new KeyValuePairSerializable<string, string>(p)).ToArray();
}
set
{
Parameters = value?.ToDictionary(i => i.Key, i => i.Value);
}
}
Just the property must be the array, not the List.
Your Ruby is installed in /usr/local/Cellar/ruby/...
.
That is a restricted path and can only be written to when you use elevated privileges, either by running as root or by using sudo
. I won't recommend you run things as root since you don't understand how paths and permissions work. You can use sudo gem install jekyll
, which will temporarily elevate your permissions, giving your command the rights needed to write to that directory.
However, I'd recommend you give serious thought into NOT doing that, and instead use your RVM to install Ruby into your own home directory, where you'll automatically be able to install Rubies and gems without permission issues. See the directions for installing into a local RVM sandbox in "Single-User installations".
Because you have RVM in your ~/.bash_profile
, but it doesn't show up in your Gem environment listing, I suspect you either haven't followed the directions for installing RVM correctly, or you haven't used the all-important command:
rvm use 2.0.0 --default
to configure a default Ruby.
For most users, the "Single-User installation" is the way to go. If you have to use sudo
with that configuration you've done something wrong.
Along with the above answers Try this for min and max length:
In Model
[StringLength(13, MinimumLength=10)]
public string MobileNo { get; set; }
In view
<div class="col-md-8">
@Html.TextBoxFor(m => m.MobileNo, new { @class = "form-control" , type="phone"})
@Html.ValidationMessageFor(m => m.MobileNo,"Invalid Number")
@Html.CheckBoxFor(m => m.IsAgreeTerms, new {@checked="checked",style="display:none" })
</div>
Try to set the element's value using the executeScript
method of JavascriptExecutor:
WebDriver driver = new FirefoxDriver();
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("document.getElementById('elementID').setAttribute('value', 'new value for element')");
Method 1:USE PDO query method
$stmt = $db->query('SELECT id FROM Employee where name ="'.$name.'"');
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
Getting Row Count
$stmt = $db->query('SELECT id FROM Employee where name ="'.$name.'"');
$row_count = $stmt->rowCount();
echo $row_count.' rows selected';
Method 2: Statements With Parameters
$stmt = $db->prepare("SELECT id FROM Employee WHERE name=?");
$stmt->execute(array($name));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
Method 3:Bind parameters
$stmt = $db->prepare("SELECT id FROM Employee WHERE name=?");
$stmt->bindValue(1, $name, PDO::PARAM_STR);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
**bind with named parameters**
$stmt = $db->prepare("SELECT id FROM Employee WHERE name=:name");
$stmt->bindValue(':name', $name, PDO::PARAM_STR);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
or
$stmt = $db->prepare("SELECT id FROM Employee WHERE name=:name");
$stmt->execute(array(':name' => $name));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
Want to know more look at this link
Try this out - https://github.com/satyapaul/jpath/blob/master/JSONDataReader.java
It's a very simple implementation on similar line of xpath for xml. It's names as jpath.
With python >= 3.5
you can use mock_object.assert_not_called()
.
If you have an ES6 compliant browser you can use:
The difference between ascending and descending sort order is the sign of the value returned by your compare function:
var ascending = homes.sort((a, b) => Number(a.price) - Number(b.price));
var descending = homes.sort((a, b) => Number(b.price) - Number(a.price));
Here's a working code snippet:
var homes = [{_x000D_
"h_id": "3",_x000D_
"city": "Dallas",_x000D_
"state": "TX",_x000D_
"zip": "75201",_x000D_
"price": "162500"_x000D_
}, {_x000D_
"h_id": "4",_x000D_
"city": "Bevery Hills",_x000D_
"state": "CA",_x000D_
"zip": "90210",_x000D_
"price": "319250"_x000D_
}, {_x000D_
"h_id": "5",_x000D_
"city": "New York",_x000D_
"state": "NY",_x000D_
"zip": "00010",_x000D_
"price": "962500"_x000D_
}];_x000D_
_x000D_
homes.sort((a, b) => Number(a.price) - Number(b.price));_x000D_
console.log("ascending", homes);_x000D_
_x000D_
homes.sort((a, b) => Number(b.price) - Number(a.price));_x000D_
console.log("descending", homes);
_x000D_
That is perfectly acceptable, probably even the standard.
(public/private) static final TYPE NAME = VALUE;
where TYPE
is the type, NAME
is the name in all caps with underscores for spaces, and VALUE
is the constant value;
I highly recommend NOT putting your constants in their own classes or interfaces.
As a side note: Variables that are declared final and are mutable can still be changed; however, the variable can never point at a different object.
For example:
public static final Point ORIGIN = new Point(0,0);
public static void main(String[] args){
ORIGIN.x = 3;
}
That is legal and ORIGIN
would then be a point at (3, 0).
Ok @Adam and @Kimvais were right, paramiko cannot parse .ppk files.
So the way to go (thanks to @JimB too) is to convert .ppk file to openssh private key format; this can be achieved using Puttygen as described here.
Then it's very simple getting connected with it:
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('<hostname>', username='<username>', password='<password>', key_filename='<path/to/openssh-private-key-file>')
stdin, stdout, stderr = ssh.exec_command('ls')
print stdout.readlines()
ssh.close()
In SQL Server 2012 and higher, this will format a number with commas:
select format([Number], 'N0')
You can also change 0
to the number of decimal places you want.
You can add a callback function to your list of get_category(...) parameters.
Ex:
get_categories(number, callback){
this.http.post( url, body, {headers: headers, withCredentials:true})
.subscribe(
response => {
this.total = response.json();
callback();
}, error => {
}
);
}
And then you can just call get_category(...) like this:
this.get_category(1, name_of_function);
Try this:
^(.+)\/([^\/]+)$
EDIT: escaped the forward slash to prevent problems when copy/pasting the Regex
try
@font-face {
font-family: 'icomoon';
src: asset-url('icomoon.eot');
src: asset-url('icomoon.eot?#iefix') format('embedded-opentype'),
asset-url('icomoon.ttf') format('truetype'),
asset-url('icomoon.woff') format('woff'),
asset-url('icomoon.svg#icomoon') format('svg');
font-weight: normal;
font-style: normal;
}
and rename your file to application.css.scss
When you decide between fixed width and fluid width you need to think in terms of your ENTIRE page. Generally, you want to pick one or the other, but not both. The examples you listed in your question are, in-fact, in the same fixed-width page. In other words, the Scaffolding page is using a fixed-width layout. The fixed grid and fluid grid on the Scaffolding page are not meant to be examples, but rather the documentation for implementing fixed and fluid width layouts.
The proper fixed width example is here. The proper fluid width example is here.
When observing the fixed width example, you should not see the content changing sizes when your browser is greater than 960px wide. This is the maximum (fixed) width of the page. Media queries in a fixed-width design will designate the minimum widths for particular styles. You will see this in action when you shrink your browser window and see the layout snap to a different size.
Conversely, the fluid-width layout will always stretch to fit your browser window, no matter how wide it gets. The media queries indicate when the styles change, but the width of containers are always a percentage of your browser window (rather than a fixed number of pixels).
The 'responsive' media queries are all ready to go. You just need to decide if you want to use a fixed width or fluid width layout for your page.
Previously, in bootstrap 2, you had to use row-fluid
inside a fluid container and row
inside a fixed container. With the introduction of bootstrap 3, row-fluid
was removed, do no longer use it.
EDIT: As per the comments, some jsFiddles for:
These fiddles are completely Bootstrap-free, based on pure CSS media queries, which makes them a good starting point, for anyone willing to craft similar solution without using Twitter Bootstrap.
Following is the working code.
<input type='file' onchange="readURL(this);" />
<img id="ShowImage" src="#" />
Javascript:
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#ShowImage')
.attr('src', e.target.result)
.width(150)
.height(200);
};
reader.readAsDataURL(input.files[0]);
}
}
I've found that using:
<img src="file://null">
will not make a request and validates correctly.
The browsers will simply block the access to the local file system.
But there might be an error displayed in console log in Chrome for example:
Not allowed to load local resource: file://null/
You can fix that.
Link PYTHONSTARTUP
to a python file with the following
# Make exit work as expected
type(exit).__repr__ = type(exit).__call__
How does this work?
The python command line is a read-evaluate-print-loop, that is when you type text it will read that text, evaluate it, and eventually print the result.
When you type exit()
it evaluates to a callable object of type site.Quitter
and calls its __call__
function which exits the system. When you type exit
it evaluates to the same callable object, without calling it the object is printed which in turn calls __repr__
on the object.
We can take advantage of this by linking __repr__
to __call__
and thus get the expected behavior of exiting the system even when we type exit
without parentheses.
You can use int casting which allows the base specification.
int(b, 2) # Convert a binary string to a decimal int.
@Lauren?iu Dascalu's answer explains how / why you get a ClassCastException.
Your exception message looks rather suspicious to me, but it might help you to know that "[Lcom.rsa.authagent.authapi.realmstat.AUTHw" means that the actual type of the object that you were trying to cast was com.rsa.authagent.authapi.realmstat.AUTHw[]
; i.e. it was an array object.
Normally, the next steps to solving a problem like this are:
Java 8 supports default methods in interfaces. And in JDK 8 a lot of old interfaces now have new default methods. For example, now in CharSequence we have chars and codePoints methods.
If source level of your project is lower than 1.8, then compiler doesn't allow you to use default methods in interfaces. So it cannot compile classes that directly on indirectly depend on this interfaces.
If I get your problem right, then you have two solutions. First solution is to rollback to JDK 7, then you will use old CharSequence interface without default methods. Second solution is to set source level of your project to 1.8, then your compiler will not complain about default methods in interfaces.
In addition, for those looking to replace more than one character in a column, you can do it using regular expressions:
import re
chars_to_remove = ['.', '-', '(', ')', '']
regular_expression = '[' + re.escape (''. join (chars_to_remove)) + ']'
df['string_col'].str.replace(regular_expression, '', regex=True)
Curent class .dropdown-submenu > .dropdown-menu
have left: 100%;
. So, if you want to open submenu on the left side, override those settings to negative left position. For example left: -95%;
. Now you will get submenu on the left side, and you can tweak other settings to get perfect preview.
Here is DEMO
EDIT: OP's question and my answer are from august 2012. Meanwhile, Bootstrap changed, so now you have .pull-left class. Back then, my answer was correct. Now you don't have to manually set css, you have that .pull-left class.
EDIT 2: Demos aren't working, because Bootstrap changed their URL's. Just change external resources in jsfiddle and replace them with new ones.
You can assign the DataFrame
to a filtered version of itself:
df = df[df.score > 50]
This is faster than drop
:
%%timeit
test = pd.DataFrame({'x': np.random.randn(int(1e6))})
test = test[test.x < 0]
# 54.5 ms ± 2.02 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
%%timeit
test = pd.DataFrame({'x': np.random.randn(int(1e6))})
test.drop(test[test.x > 0].index, inplace=True)
# 201 ms ± 17.9 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
%%timeit
test = pd.DataFrame({'x': np.random.randn(int(1e6))})
test = test.drop(test[test.x > 0].index)
# 194 ms ± 7.03 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
the am giving you is the code for trigger for INSERT, UPDATE and DELETE this works fine on Microsoft SQL SERVER 2008 and onwards database i am using is Northwind
/* comment section first create a table to keep track of Insert, Delete, Update
create table Emp_Audit(
EmpID int,
Activity varchar(20),
DoneBy varchar(50),
Date_Time datetime NOT NULL DEFAULT GETDATE()
);
select * from Emp_Audit*/
create trigger Employee_trigger
on Employees
after UPDATE, INSERT, DELETE
as
declare @EmpID int,@user varchar(20), @activity varchar(20);
if exists(SELECT * from inserted) and exists (SELECT * from deleted)
begin
SET @activity = 'UPDATE';
SET @user = SYSTEM_USER;
SELECT @EmpID = EmployeeID from inserted i;
INSERT into Emp_Audit(EmpID,Activity, DoneBy) values (@EmpID,@activity,@user);
end
If exists (Select * from inserted) and not exists(Select * from deleted)
begin
SET @activity = 'INSERT';
SET @user = SYSTEM_USER;
SELECT @EmpID = EmployeeID from inserted i;
INSERT into Emp_Audit(EmpID,Activity, DoneBy) values(@EmpID,@activity,@user);
end
If exists(select * from deleted) and not exists(Select * from inserted)
begin
SET @activity = 'DELETE';
SET @user = SYSTEM_USER;
SELECT @EmpID = EmployeeID from deleted i;
INSERT into Emp_Audit(EmpID,Activity, DoneBy) values(@EmpID,@activity,@user);
end
What it correct way of installing SmartGit on Ubuntu? Thus I can have normal icon
In smartgit/bin folder, there's a shell script waiting for you: add-menuitem.sh. It does just that.
The key to debugging situations like these is to run the subquery/inline view on its' own to see what the output is:
SELECT TOP 1
dm.marker_value,
dum.profile_id
FROM DPS_USR_MARKERS dum (NOLOCK)
JOIN DPS_MARKERS dm (NOLOCK) ON dm.marker_id= dum.marker_id
AND dm.marker_key = 'moneyBackGuaranteeLength'
ORDER BY dm.creation_date
Running that, you would see that the profile_id
value didn't match the u.id
value of u162231993
, which would explain why any mbg
references would return null
(thanks to the left join; you wouldn't get anything if it were an inner join).
You've coded yourself into a corner using TOP
, because now you have to tweak the query if you want to run it for other users. A better approach would be:
SELECT u.id,
x.marker_value
FROM DPS_USER u
LEFT JOIN (SELECT dum.profile_id,
dm.marker_value,
dm.creation_date
FROM DPS_USR_MARKERS dum (NOLOCK)
JOIN DPS_MARKERS dm (NOLOCK) ON dm.marker_id= dum.marker_id
AND dm.marker_key = 'moneyBackGuaranteeLength'
) x ON x.profile_id = u.id
JOIN (SELECT dum.profile_id,
MAX(dm.creation_date) 'max_create_date'
FROM DPS_USR_MARKERS dum (NOLOCK)
JOIN DPS_MARKERS dm (NOLOCK) ON dm.marker_id= dum.marker_id
AND dm.marker_key = 'moneyBackGuaranteeLength'
GROUP BY dum.profile_id) y ON y.profile_id = x.profile_id
AND y.max_create_date = x.creation_date
WHERE u.id = 'u162231993'
With that, you can change the id
value in the where
clause to check records for any user in the system.
TL;DR
A Function is a piece of code to run.
A Method is a Function inside an Object.
Example of a function:
function sum(){
console.log("sum")l
}
Example of a Method:
const obj = {
a:1,
b:2,
sum(){
}
}
So thats why we say that a "this" keyword inside a Function is not very useful unless we use it with call, apply or bind .. because call, apply, bind will call that function as a method inside object ==> basically it converts function to method
Wamp Server localhost not working. problems port 80 is closed. Icon Color Yellow
Solution:
wamp icon click > Apache > Service > Service Install
wamp icon click > All Services Restart
Icon Green its Work
I got same error on my Xcode 6.1.1 for a project downloaded from gitHub which was committed 4 years ago. For me, setting Architectures to the default value Standard architectures(armv7,arm64) and Compiler for C/C++/Objective-C to Default Compiler in Building Settings worked.
The legacy solution, before 1.6, was to use .attr
and handle the returned value as a bool
. The main problem is that the returned type of .attr
has changed to string
, and therefore the comparison with == true
is broken (see http://jsfiddle.net/2vene/1/ (and switch the jquery-version)).
With 1.6 .prop
was introduced, which returns a bool
.
Nevertheless, I suggest to use .is()
, as the returned type is intrinsically bool
, like:
$('#dropUnit').is(':disabled');
$('#dropUnit').is(':enabled');
Furthermore .is()
is much more natural (in terms of "natural language") and adds more conditions than a simple attribute-comparison (eg: .is(':last')
, .is(':visible')
, ... please see documentation on selectors).
You have to use GetThumbnailImage
method in the Image
class:
https://msdn.microsoft.com/en-us/library/8t23aykb%28v=vs.110%29.aspx
Here's a rough example that takes an image file and makes a thumbnail image from it, then saves it back to disk.
Image image = Image.FromFile(fileName);
Image thumb = image.GetThumbnailImage(120, 120, ()=>false, IntPtr.Zero);
thumb.Save(Path.ChangeExtension(fileName, "thumb"));
It is in the System.Drawing namespace (in System.Drawing.dll).
Behavior:
If the Image contains an embedded thumbnail image, this method retrieves the embedded thumbnail and scales it to the requested size. If the Image does not contain an embedded thumbnail image, this method creates a thumbnail image by scaling the main image.
Important: the remarks section of the Microsoft link above warns of certain potential problems:
The
GetThumbnailImage
method works well when the requested thumbnail image has a size of about 120 x 120 pixels. If you request a large thumbnail image (for example, 300 x 300) from an Image that has an embedded thumbnail, there could be a noticeable loss of quality in the thumbnail image.It might be better to scale the main image (instead of scaling the embedded thumbnail) by calling the
DrawImage
method.
Another thing to notice is you are trying to convert a date in mm/dd/yyyy but if you have any plans of comparing this converted date to some other date then make sure to convert it in yyyy-mm-dd format only since to_char literally converts it into a string and with any other format we will get undesired result. For any more explanation follow this: Comparing Dates in Oracle SQL
As far as I can tell, there are three main contenders: Table-Valued Parameters, delimited list string, and JSON string.
Since 2016, you can use the built-in STRING_SPLIT if you want the delimited route: https://docs.microsoft.com/en-us/sql/t-sql/functions/string-split-transact-sql
That would probably be the easiest/most straightforward/simple approach.
Also since 2016, JSON can be passed as a nvarchar and used with OPENJSON: https://docs.microsoft.com/en-us/sql/t-sql/functions/openjson-transact-sql
That's probably best if you have a more structured data set to pass that may be significantly variable in its schema.
TVPs, it seems, used to be the canonical way to pass more structured parameters, and they are still good if you need that structure, explicitness, and basic value/type checking. They can be a little more cumbersome on the consumer side, though. If you don't have 2016+, this is probably the default/best option.
I think it's a trade off between any of these concrete considerations as well as your preference for being explicit about the structure of your params, meaning even if you have 2016+, you may prefer to explicitly state the type/schema of the parameter rather than pass a string and parse it somehow.
I have to find distinct rows with the following details
class : Scountry
columns: countryID, countryName,isactive
There is no primary key in this. I have succeeded with the followin queries
public DbSet<SCountry> country { get; set; }
public List<SCountry> DoDistinct()
{
var query = (from m in country group m by new { m.CountryID, m.CountryName, m.isactive } into mygroup select mygroup.FirstOrDefault()).Distinct();
var Countries = query.ToList().Select(m => new SCountry { CountryID = m.CountryID, CountryName = m.CountryName, isactive = m.isactive }).ToList();
return Countries;
}
you can use
moviesTitles.map((title) => Tab(text: title)).toList()
example:
bottom: new TabBar(
controller: _controller,
isScrollable: true,
tabs:
moviesTitles.map((title) => Tab(text: title)).toList()
,
),
So to start with some kind of answer : ) - You can't
I am not an expert, but as far as I understand DataFrames, they are not equal to rdd and DataFrame has no such thing as Partitioner.
Generally DataFrame's idea is to provide another level of abstraction that handles such problems itself. The queries on DataFrame are translated into logical plan that is further translated to operations on RDDs. The partitioning you suggested will probably be applied automatically or at least should be.
If you don't trust SparkSQL that it will provide some kind of optimal job, you can always transform DataFrame to RDD[Row] as suggested in of the comments.
Don't write if
statements without a corresponding else
. Once you add the else
to your fragment you'll see that your true
and false
are in fact the last expressions of the function.
def balanceMain(elem: List[Char]): Boolean =
{
if (elem.isEmpty)
if (count == 0)
true
else
false
else
if (elem.head == '(')
balanceMain(elem.tail, open, count + 1)
else....
As others have pointed out setInterval and setTimeout will do the trick. I wanted to highlight a bit more advanced technique that I learned from this excellent video by Paul Irish: http://paulirish.com/2010/10-things-i-learned-from-the-jquery-source/
For periodic tasks that might end up taking longer than the repeat interval (like an HTTP request on a slow connection) it's best not to use setInterval()
. If the first request hasn't completed and you start another one, you could end up in a situation where you have multiple requests that consume shared resources and starve each other. You can avoid this problem by waiting to schedule the next request until the last one has completed:
// Use a named immediately-invoked function expression.
(function worker() {
$.get('ajax/test.html', function(data) {
// Now that we've completed the request schedule the next one.
$('.result').html(data);
setTimeout(worker, 5000);
});
})();
For simplicity I used the success callback for scheduling. The down side of this is one failed request will stop updates. To avoid this you could use the complete callback instead:
(function worker() {
$.ajax({
url: 'ajax/test.html',
success: function(data) {
$('.result').html(data);
},
complete: function() {
// Schedule the next request when the current one's complete
setTimeout(worker, 5000);
}
});
})();
Here is the answer:
Download the "Windows Mobile Device Center" for your machine type, likely 64bit.
http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=3182
Before you run the install, change the compatibility settings to 'Windows 7'. Then install it... Then run it: You'll find it under 'WMDC'.. Your device should now recognize, when plugged in, mine did!
The other answers do a good job of recreating the default header view, but don't actually answer your main question:
is there any way to get default section header ?
There is a way - just implement tableView:willDisplayHeaderView:forSection:
in your delegate. The default header view will be passed into the second parameter, and from there you can cast it to a UITableViewHeaderFooterView
and then add/change subviews as you wish.
Obj-C
- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section
{
UITableViewHeaderFooterView *headerView = (UITableViewHeaderFooterView *)view;
// Do whatever with the header view... e.g.
// headerView.textLabel.textColor = [UIColor whiteColor]
}
Swift
override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int)
{
let headerView = view as! UITableViewHeaderFooterView
// Do whatever with the header view... e.g.
// headerView.textLabel?.textColor = UIColor.white
}
myLabel.setHorizontalAlignment(SwingConstants.CENTER);
myLabel.setVerticalAlignment(SwingConstants.CENTER);
If you cannot reconstruct the label for some reason, this is how you edit these properties of a pre-existent JLabel.
I have similar situation. In my case, it doesn't have a parent with position:relative. Just paste my solution here for those that might need.
position: fixed;
left: 0;
right: 0;
Gist with log rotation: https://gist.github.com/barsv/85c93b599a763206f47aec150fb41ca0
Usage:
. .\logger.ps1
Write-Log "debug message"
Write-Log "info message" "INFO"
To get the moving average in pandas we can use cum_sum and then divide by count.
Here is the working example:
import pandas as pd
import numpy as np
df = pd.DataFrame({'id': range(5),
'value': range(100,600,100)})
# some other similar statistics
df['cum_sum'] = df['value'].cumsum()
df['count'] = range(1,len(df['value'])+1)
df['mov_avg'] = df['cum_sum'] / df['count']
# other statistics
df['rolling_mean2'] = df['value'].rolling(window=2).mean()
print(df)
id value cum_sum count mov_avg rolling_mean2
0 0 100 100 1 100.0 NaN
1 1 200 300 2 150.0 150.0
2 2 300 600 3 200.0 250.0
3 3 400 1000 4 250.0 350.0
4 4 500 1500 5 300.0 450.0
Do this
<% for(int i = 0; i < allFestivals.size(); i+=1) { %>
<tr>
<td><%=allFestivals.get(i).getFestivalName()%></td>
</tr>
<% } %>
Better way is to use c:foreach see link jstl for each
is there a way to pass param from
navigate.goback()
and parent can listen to the params and update its state?
You can pass a callback function as parameter (as mentioned in other answers).
Here is a more clear example, when you navigate from A to B and you want B to communicate information back to A you can pass a callback (here onSelect
):
ViewA.js
import React from "react";
import { Button, Text, View } from "react-native";
class ViewA extends React.Component {
state = { selected: false };
onSelect = data => {
this.setState(data);
};
onPress = () => {
this.props.navigate("ViewB", { onSelect: this.onSelect });
};
render() {
return (
<View>
<Text>{this.state.selected ? "Selected" : "Not Selected"}</Text>
<Button title="Next" onPress={this.onPress} />
</View>
);
}
}
ViewB.js
import React from "react";
import { Button } from "react-native";
class ViewB extends React.Component {
goBack() {
const { navigation } = this.props;
navigation.goBack();
navigation.state.params.onSelect({ selected: true });
}
render() {
return <Button title="back" onPress={this.goBack} />;
}
}
Hats off for debrice - Refer to https://github.com/react-navigation/react-navigation/issues/288#issuecomment-315684617
For React Navigation v5
ViewB.js
import React from "react";
import { Button } from "react-native";
class ViewB extends React.Component {
goBack() {
const { navigation, route } = this.props;
navigation.goBack();
route.params.onSelect({ selected: true });
}
render() {
return <Button title="back" onPress={this.goBack} />;
}
}
SMTP -> FROM SERVER:
SMTP -> FROM SERVER:
SMTP -> ERROR: EHLO not accepted from server:
that's typical of trying to connect to a SSL service with a client that's not using SSL
SMTP Error: Could not authenticate.
no suprise there having failed to start an SMTP conversation authentigation is not an option,.
phpmailer doesn't do implicit SSL (aka TLS on connect, SMTPS) Short of rewriting smtp.class.php to include support for it there it no way to do what you ask.
Use port 587 with explicit SSL (aka TLS, STARTTLS) instead.
If you do it in a migration then you could probably do it like this:
# Make sure no null value exist
MyModel.where(date_column: nil).update_all(date_column: Time.now)
# Change the column to not allow null
change_column :my_models, :date_column, :datetime, null: false
Sweet Jesus. I tried all of the above things (but found my settings identical). YET ANOTHER SOLUTION if you are having issues:
http://support.microsoft.com/kb/980368
Try installing this KB for your system. If you are seeing 404s it might be because you don't have this update -- and the isapi module just isn't getting found and there's not a lot you can do about that without this!
""" to shuffle random, set random= True """
def shuffle(x,random=False):
shuffled = []
ma = x
if random == True:
rando = [ma[i] for i in np.random.randint(0,len(ma),len(ma))]
return rando
if random == False:
for i in range(len(ma)):
ave = len(ma)//3
if i < ave:
shuffled.append(ma[i+ave])
else:
shuffled.append(ma[i-ave])
return shuffled
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.hardware.GeomagneticField;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.widget.Toast;
public class LocationService extends Service {
private static final int MINUTES = 1000 * 60 * 2;
public LocationManager locationManager;
public MyLocationListener listener;
public Location previousBestLocation = null;
Context mContext;
private boolean isGpsEnabled = false;
private boolean isNetworkEnabled = false;
private GeomagneticField geoField;
private double latitude = 0.0;
private double longitude = 0.0;
@Override
public void onCreate() {
super.onCreate();
mContext = getApplicationContext();
if (locationManager == null) {
locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
}
getCurrentLocation();
}
private void getCurrentLocation() {
try {
assert locationManager != null;
isGpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
ex.printStackTrace();
}
if (!isGpsEnabled && !isNetworkEnabled) {
showSettingsAlert();
}
listener = new MyLocationListener();
try {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 0, listener);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 10000, 0, listener);
} catch (SecurityException e) {
e.printStackTrace();
}
}
private void showSettingsAlert() {
Toast.makeText(mContext, "GPS is disabled in your device. Please Enable it ?", Toast.LENGTH_LONG).show();
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(intent);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
protected boolean isBetterLocation(Location location, Location currentBestLocation) {
if (currentBestLocation == null) {
return true;
}
long timeDelta = location.getTime() - currentBestLocation.getTime();
boolean isSignificantlyNewer = timeDelta > MINUTES;
boolean isSignificantlyOlder = timeDelta < -MINUTES;
boolean isNewer = timeDelta > 0;
if (isSignificantlyNewer) {
return true;
} else if (isSignificantlyOlder) {
return false;
}
int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation.getAccuracy());
boolean isLessAccurate = accuracyDelta > 0;
boolean isMoreAccurate = accuracyDelta < 0;
boolean isSignificantlyLessAccurate = accuracyDelta > 200;
boolean isFromSameProvider = isSameProvider(location.getProvider(), currentBestLocation.getProvider());
if (isMoreAccurate) {
return true;
} else if (isNewer && !isLessAccurate) {
return true;
} else if (isNewer && !isSignificantlyLessAccurate && isFromSameProvider) {
return true;
}
return false;
}
private boolean isSameProvider(String provider1, String provider2) {
if (provider1 == null) {
return provider2 == null;
}
return provider1.equals(provider2);
}
@Override
public void onDestroy() {
super.onDestroy();
locationManager.removeUpdates(listener);
}
private void setupFinalLocationData(Location mLocation) {
if (mLocation != null) {
geoField = new GeomagneticField(
Double.valueOf(mLocation.getLatitude()).floatValue(),
Double.valueOf(mLocation.getLongitude()).floatValue(),
Double.valueOf(mLocation.getAltitude()).floatValue(),
System.currentTimeMillis()
);
latitude = mLocation.getLatitude();
longitude = mLocation.getLongitude();
//Update latitude and longtitude in SharedPreference...
}
}
public class MyLocationListener implements LocationListener {
public void onLocationChanged(final Location loc) {
if (isBetterLocation(loc, previousBestLocation)) {
setupFinalLocationData(loc);
}
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
}
I changed a few things to work with Option Explicit
, and the code ran fine against a cell containing "abc.123"
, which returned "abc.12,"
. There were no compile errors.
Option Explicit ' This is new
Public Function ProcessString(input_string As String) As String
' The temp string used throughout the function
Dim temp_string As String
Dim i As Integer ' This is new
Dim return_string As String ' This is new
For i = 1 To Len(input_string)
temp_string = Mid(input_string, i, 1)
If temp_string Like "[A-Z, a-z, 0-9, :, -]" Then
return_string = return_string & temp_string
End If
Next i
return_string = Mid(return_string, 1, (Len(return_string) - 1))
ProcessString = return_string & ", "
End Function
I'll suggest you post more of your relevant code (that calls this function). You've stated that last_name is a String, but it appears that may not be the case. Step through your code line by line and ensure that this is actually the case.
It is valuable to additionally note, that PHP will populate all the $_GET
parameters even when you send a proper request of other type.
Methods in above replies are completely correct, however if you want to additionaly check for GET
parameters while handling POST
, DELETE
, PUT
, etc. request, you need to check the size of $_GET
array.
make use of the jackson JSON processor
ObjectMapper mapper = new ObjectMapper();
Book book = mapper.readValue(request.getInputStream(),Book.class);
There is a super simple way.
in BaseActivity, Activity or Fragment override attachBaseContext
override fun attachBaseContext(context: Context) {
super.attachBaseContext(context.changeLocale("tr"))
}
extension
fun Context.changeLocale(language:String): Context {
val locale = Locale(language)
Locale.setDefault(locale)
val config = this.resources.configuration
config.setLocale(locale)
return createConfigurationContext(config)
}
A couple of things to note:
If you want it to be treated as a proper ASP.NET postback, you can call the methods supplied by the framework, namely __doPostBack(eventTarget, eventArgument)
:
<div name="mysubmitbutton" id="mysubmitbutton" class="customButton"
onclick="javascript:__doPostBack('<%=mysubmitbutton.ClientID %>', 'MyCustomArgument');">
Button Text
</div>
You want a config.site file. Try:
$ mkdir -p ~/local/share $ cat << EOF > ~/local/share/config.site CPPFLAGS=-I$HOME/local/include LDFLAGS=-L$HOME/local/lib ... EOF
Whenever you invoke an autoconf generated configure script with --prefix=$HOME/local, the config.site will be read and all the assignments will be made for you. CPPFLAGS and LDFLAGS should be all you need, but you can make any other desired assignments as well (hence the ... in the sample above). Note that -I flags belong in CPPFLAGS and not in CFLAGS, as -I is intended for the pre-processor and not the compiler.
The example Java data structure in the original question does not match the description of the JSON structure in the comment.
The JSON is described as
"an array of {object with an array of {object}}".
In terms of the types described in the question, the JSON translated into a Java data structure that would match the JSON structure for easy deserialization with Gson is
"an array of {TypeDTO object with an array of {ItemDTO object}}".
But the Java data structure provided in the question is not this. Instead it's
"an array of {TypeDTO object with an array of an array of {ItemDTO object}}".
A two-dimensional array != a single-dimensional array.
This first example demonstrates using Gson to simply deserialize and serialize a JSON structure that is "an array of {object with an array of {object}}".
input.json Contents:
[
{
"id":1,
"name":"name1",
"items":
[
{"id":2,"name":"name2","valid":true},
{"id":3,"name":"name3","valid":false},
{"id":4,"name":"name4","valid":true}
]
},
{
"id":5,
"name":"name5",
"items":
[
{"id":6,"name":"name6","valid":true},
{"id":7,"name":"name7","valid":false}
]
},
{
"id":8,
"name":"name8",
"items":
[
{"id":9,"name":"name9","valid":true},
{"id":10,"name":"name10","valid":false},
{"id":11,"name":"name11","valid":false},
{"id":12,"name":"name12","valid":true}
]
}
]
Foo.java:
import java.io.FileReader;
import java.util.ArrayList;
import com.google.gson.Gson;
public class Foo
{
public static void main(String[] args) throws Exception
{
Gson gson = new Gson();
TypeDTO[] myTypes = gson.fromJson(new FileReader("input.json"), TypeDTO[].class);
System.out.println(gson.toJson(myTypes));
}
}
class TypeDTO
{
int id;
String name;
ArrayList<ItemDTO> items;
}
class ItemDTO
{
int id;
String name;
Boolean valid;
}
This second example uses instead a JSON structure that is actually "an array of {TypeDTO object with an array of an array of {ItemDTO object}}" to match the originally provided Java data structure.
input.json Contents:
[
{
"id":1,
"name":"name1",
"items":
[
[
{"id":2,"name":"name2","valid":true},
{"id":3,"name":"name3","valid":false}
],
[
{"id":4,"name":"name4","valid":true}
]
]
},
{
"id":5,
"name":"name5",
"items":
[
[
{"id":6,"name":"name6","valid":true}
],
[
{"id":7,"name":"name7","valid":false}
]
]
},
{
"id":8,
"name":"name8",
"items":
[
[
{"id":9,"name":"name9","valid":true},
{"id":10,"name":"name10","valid":false}
],
[
{"id":11,"name":"name11","valid":false},
{"id":12,"name":"name12","valid":true}
]
]
}
]
Foo.java:
import java.io.FileReader;
import java.util.ArrayList;
import com.google.gson.Gson;
public class Foo
{
public static void main(String[] args) throws Exception
{
Gson gson = new Gson();
TypeDTO[] myTypes = gson.fromJson(new FileReader("input.json"), TypeDTO[].class);
System.out.println(gson.toJson(myTypes));
}
}
class TypeDTO
{
int id;
String name;
ArrayList<ItemDTO> items[];
}
class ItemDTO
{
int id;
String name;
Boolean valid;
}
Regarding the remaining two questions:
is Gson extremely fast?
Not compared to other deserialization/serialization APIs. Gson has traditionally been amongst the slowest. The current and next releases of Gson reportedly include significant performance improvements, though I haven't looked for the latest performance test data to support those claims.
That said, if Gson is fast enough for your needs, then since it makes JSON deserialization so easy, it probably makes sense to use it. If better performance is required, then Jackson might be a better choice to use. It offers much (maybe even all) of the conveniences of Gson.
Or am I better to stick with what I've got working already?
I wouldn't. I would most always rather have one simple line of code like
TypeDTO[] myTypes = gson.fromJson(new FileReader("input.json"), TypeDTO[].class);
...to easily deserialize into a complex data structure, than the thirty lines of code that would otherwise be needed to map the pieces together one component at a time.
I guess this should be quick and can be used with a Python API:
git branch --contains HEAD
* master
You can, if you want, use standalone strings for multi-line comments — I've always thought that prettier than if (FALSE) { }
blocks. The string will get evaluated and then discarded, so as long as it's not the last line in a function nothing will happen.
"This function takes a value x, and does things and returns things that
take several lines to explain"
doEverythingOften <- function(x) {
# Non! Comment it out! We'll just do it once for now.
"if (x %in% 1:9) {
doTenEverythings()
}"
doEverythingOnce()
...
return(list(
everythingDone = TRUE,
howOftenDone = 1
))
}
The main limitation is that when you're commenting stuff out, you've got to watch your quotation marks: if you've got one kind inside, you'll have to use the other kind for the comment; and if you've got something like "strings with 'postrophes" inside that block, then there's no way this method is a good idea. But then there's still the if (FALSE)
block.
The other limitation, one that both methods have, is that you can only use such blocks in places where an expression would be syntactically valid - no commenting out parts of lists, say.
Regarding what do in which IDE: I'm a Vim user, and I find NERD Commenter an utterly excellent tool for quickly commenting or uncommenting multiple lines. Very user-friendly, very well-documented.
Lastly, at the R prompt (at least under Linux), there's the lovely Alt-Shift-# to comment the current line. Very nice to put a line 'on hold', if you're working on a one-liner and then realise you need a prep step first.
Note, that starting from c++20 std::string will finally provide starts_with and ends_with. Seems like there is a chance that by c++30 strings in c++ might finally become usable, if you aren't reading this from distant future, you can use these startsWith/endsWith with C++17:
#if __cplusplus >= 201703L // C++17 and later
#include <string_view>
static bool endsWith(std::string_view str, std::string_view suffix)
{
return str.size() >= suffix.size() && 0 == str.compare(str.size()-suffix.size(), suffix.size(), suffix);
}
static bool startsWith(std::string_view str, std::string_view prefix)
{
return str.size() >= prefix.size() && 0 == str.compare(0, prefix.size(), prefix);
}
#endif // C++17
If you are stuck with older C++, you may use these:
#if __cplusplus < 201703L // pre C++17
#include <string>
static bool endsWith(const std::string& str, const std::string& suffix)
{
return str.size() >= suffix.size() && 0 == str.compare(str.size()-suffix.size(), suffix.size(), suffix);
}
static bool startsWith(const std::string& str, const std::string& prefix)
{
return str.size() >= prefix.size() && 0 == str.compare(0, prefix.size(), prefix);
}
and some extra helper overloads:
static bool endsWith(const std::string& str, const char* suffix, unsigned suffixLen)
{
return str.size() >= suffixLen && 0 == str.compare(str.size()-suffixLen, suffixLen, suffix, suffixLen);
}
static bool endsWith(const std::string& str, const char* suffix)
{
return endsWith(str, suffix, std::string::traits_type::length(suffix));
}
static bool startsWith(const std::string& str, const char* prefix, unsigned prefixLen)
{
return str.size() >= prefixLen && 0 == str.compare(0, prefixLen, prefix, prefixLen);
}
static bool startsWith(const std::string& str, const char* prefix)
{
return startsWith(str, prefix, std::string::traits_type::length(prefix));
}
#endif
IMO, c++ strings are clearly dysfunctional, and weren't made to be used in real world code. But there is a hope that this will get better at least.
You have to modify the control template instead of ItemsPanelTemplate:
<ItemsControl >
<ItemsControl.Template>
<ControlTemplate>
<ScrollViewer x:Name="ScrollViewer" Padding="{TemplateBinding Padding}">
<ItemsPresenter />
</ScrollViewer>
</ControlTemplate>
</ItemsControl.Template>
</ItemsControl>
Maybe, your code does not working because StackPanel has own scrolling functionality. Try to use StackPanel.CanVerticallyScroll property.
in your css :
#txtComputer {
font-size: 24px;
}
You can style an input entirely (background, color, etc.) and even use the hover event.
I faced same issue. After downloading everything, still 'punkt' error was there. I searched package on my windows machine at C:\Users\vaibhav\AppData\Roaming\nltk_data\tokenizers and I can see 'punkt.zip' present there. I realized that somehow the zip has not been extracted into C:\Users\vaibhav\AppData\Roaming\nltk_data\tokenizers\punk. Once I extracted the zip, it worked like music.
This is just main
and Ctrl-Space.
PostgreSQL GIS extensions might be helpful - as in, it may already implement much of the functionality you are thinking of implementing.
Here is an extension method for setting unique indexes more fluently:
public static class MappingExtensions
{
public static PrimitivePropertyConfiguration IsUnique(this PrimitivePropertyConfiguration configuration)
{
return configuration.HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute { IsUnique = true }));
}
}
Usage:
modelBuilder
.Entity<Person>()
.Property(t => t.Name)
.IsUnique();
Will generate migration such as:
public partial class Add_unique_index : DbMigration
{
public override void Up()
{
CreateIndex("dbo.Person", "Name", unique: true);
}
public override void Down()
{
DropIndex("dbo.Person", new[] { "Name" });
}
}
Src: Creating Unique Index with Entity Framework 6.1 fluent API
Use Eclipse with EPIC: It gives you a nice IDE with debugging possibilities, including the ability to place breakpoints and the Perl Expression View
for inspecting the value of variables.
This was pretty well answered over here: How to make a YouTube embedded video a full page width one?
If you add '?rel=0&autoplay=1' to the end of the url in the embed code (like this)
<iframe id="video" src="//www.youtube.com/embed/5iiPC-VGFLU?rel=0&autoplay=1" frameborder="0" allowfullscreen></iframe>
of the video it should play on load. Here's a demo over at jsfiddle.
get matched string back or false
function preg_match (regex, str) {
if (new RegExp(regex).test(str)){
return regex.exec(str);
}
return false;
}
In addition to all the wonderful answers here, I'd like to throw in a special mention for the MySQLi and PDO libraries.
In order to...
The best option is to configure the libraries to throw exceptions.
Add this near the top of your script
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
This is best placed before you use new mysqli()
or mysqli_connect()
.
Set the PDO::ATTR_ERRMODE
attribute to PDO::ERRMODE_EXCEPTION
on your connection instance. You can either do this in the constructor
$pdo = new PDO('driver:host=localhost;...', 'username', 'password', [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
]);
or after creation
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
What does self do? What is it meant to be? Is it mandatory?
The first argument of every class method, including init, is always a reference to the current instance of the class. By convention, this argument is always named self
. In the init method, self
refers to the newly created object; in other class methods, it refers to the instance whose method was called.
Python doesn't force you on using "self". You can give it any name you want. But remember the first argument in a method definition is a reference to the object. Python adds the self
argument to the list for you; you do not need to include it when you call the methods.
if you didn't provide self in init method then you will get an error
TypeError: __init___() takes no arguments (1 given)
What does the init method do? Why is it necessary? (etc.)
init
is short for initialization. It is a constructor which gets called when you make an instance of the class and it is not necessary. But usually it our practice to write init method for setting default state of the object. If you are not willing to set any state of the object initially then you don't need to write this method.
Although I take the risk of not being popular I say they are not useful nowadays.
I think they were well intended and useful in the past when for example DELETE told the server to delete the resource found at supplied URL and PUT (with its sibling PATCH) told the server to do update in an idempotent manner.
Things evolved and URLs became virtual (see url rewriting for example) making resources lose their initial meaning of real folder/subforder/file and so, CRUD action verbs covered by HTTP protocol methods (GET, POST, PUT/PATCH, DELETE) lost track.
Let's take an example:
On the left side is not written the HTTP method, essentially it doesn't matter (POST and GET are enough) and on the right side appropriate HTTP methods are used.
Right side looks elegant, clean and professional. Imagine now you have to maintain a code that's been using the elegant API and you have to search where deletion call is done. You'll search for "api/entity" and among results you'll have to see which one is doing DELETE. Or even worse, you have a junior programmer which by mistake switched PUT with DELETE and as URL is the same shit happened.
In my opinion putting the action verb in the URL has advantages over using the appropriate HTTP method for that action even if it's not so elegant. If you want to see where delete call is made you just have to search for "api/entity/delete" and you'll find it straight away.
Building an API without the whole HTTP array of methods makes it easier to be consumed and maintained afterwards
Followed code worked for me:
$mail = new PHPMailer(true);
$mail->isSMTP();// Set mailer to use SMTP
$mail->CharSet = "utf-8";// set charset to utf8
$mail->SMTPAuth = true;// Enable SMTP authentication
$mail->SMTPSecure = 'tls';// Enable TLS encryption, `ssl` also accepted
$mail->Host = 'smtp.gmail.com';// Specify main and backup SMTP servers
$mail->Port = 587;// TCP port to connect to
$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
)
);
$mail->isHTML(true);// Set email format to HTML
$mail->Username = 'Sender Email';// SMTP username
$mail->Password = 'Sender Email Password';// SMTP password
$mail->setFrom('[email protected]', 'John Smith');//Your application NAME and EMAIL
$mail->Subject = 'Test';//Message subject
$mail->MsgHTML('HTML code');// Message body
$mail->addAddress('User Email', 'User Name');// Target email
$mail->send();
I had the same issue and I solved it by using:
display: inline-block;
on the div
in question.
Try experimenting with something like this also:
HTML
<ul class="inlineList">
<li>She</li>
<li>Needs</li>
<li>More Padding, Captain!</li>
</ul>
CSS
.inlineList {
display: flex;
flex-direction: row;
/* Below sets up your display method: flex-start|flex-end|space-between|space-around */
justify-content: flex-start;
/* Below removes bullets and cleans white-space */
list-style: none;
padding: 0;
/* Bonus: forces no word-wrap */
white-space: nowrap;
}
/* Here, I got you started.
li {
padding-top: 50px;
padding-bottom: 50px;
padding-left: 50px;
padding-right: 50px;
}
*/
I made a codepen to illustrate: http://codepen.io/agm1984/pen/mOxaEM
Three important steps - How to Task Schedule an excel.xls(m) file
simply:
IN MORE DETAIL...
`
' a .vbs file is just a text file containing visual basic code that has the extension renamed from .txt to .vbs
'Write Excel.xls Sheet's full path here
strPath = "C:\RodsData.xlsm"
'Write the macro name - could try including module name
strMacro = "Update" ' "Sheet1.Macro2"
'Create an Excel instance and set visibility of the instance
Set objApp = CreateObject("Excel.Application")
objApp.Visible = True ' or False
'Open workbook; Run Macro; Save Workbook with changes; Close; Quit Excel
Set wbToRun = objApp.Workbooks.Open(strPath)
objApp.Run strMacro ' wbToRun.Name & "!" & strMacro
wbToRun.Save
wbToRun.Close
objApp.Quit
'Leaves an onscreen message!
MsgBox strPath & " " & strMacro & " macro and .vbs successfully completed!", vbInformation
'
`
set Program/script: = C:\Windows\System32\cscript.exe
set Add arguments (optional): = C:\MyVbsFile.vbs
That should work.
Let me know!
Rod Bowen
userType = (user.Type == 0) ? "Admin" : (user.type == 1) ? "User" : "Admin";
should do the trick.
Open terminal and typin a2enmod rewrite
, It will enable your mod_rewrite
module for Apache.
Then go to /etc/apache2/sites-available
and edit default file. (For this you must have writable permissions to this file and sites-available folder.)
Replace below with existing lines 4 to 14
DocumentRoot /var/www
<Directory />
Options FollowSymLinks
AllowOverride All
</Directory>
<Directory /var/www/>
Options Indexes FollowSymLinks MultiViews
AllowOverride All
Order allow,deny
allow from all
</Directory>
Now restart your apache by /etc/init.d/apache2 restart
or service apache2 restart
Take clean URL test again and this time it will be passed.
Check out Padolsey's article on DOM find and replace, as well as the library to implement the described algorithm.
In this sample usage, I replace all text inside a <div id="content">
that looks like a US telephone number with a tel:
scheme link:
findAndReplaceDOMText(document.getElementById('content'), {
find:/\b(\d\d\d-\d\d\d-\d\d\d\d)\b/g,
replace:function (portion) {
var a = document.createElement('a');
a.className = 'telephone';
a.href = 'tel:' + portion.text.replace(/\D/g, '');
a.textContent = portion.text;
return a;
}
});
After my previous answer disaster, I'm going to try something else.
List<Model> usrList =
(list.Where(n => n.application == "applicationame").ToList());
usrList.ForEach(n => n.users.RemoveAll(n => n.surname != "surname"));
I had the same problem and I solved by using the postcast server. You can install it locally and use it.
By default mysqldump
always creates the CREATE DATABASE IF NOT EXISTS db_name;
statement at the beginning of the dump file.
[EDIT] Few things about the mysqldump
file and it's options:
--all-databases
, -A
Dump all tables in all databases. This is the same as using the --databases
option and naming all the databases on the command line.
--add-drop-database
Add a DROP DATABASE
statement before each CREATE DATABASE
statement. This option is typically used in conjunction with the --all-databases
or --databases
option because no CREATE DATABASE
statements are written unless one of those options is specified.
--databases
, -B
Dump several databases. Normally, mysqldump
treats the first name argument on the command line as a database name and following names as table names. With this option, it treats all name arguments as database names. CREATE DATABASE
and USE
statements are included in the output before each new database.
--no-create-db
, -n
This option suppresses the CREATE DATABASE
statements that are otherwise included in the output if the --databases
or --all-databases
option is given.
Some time ago, there was similar question actually asking about not having such statement on the beginning of the file (for XML file). Link to that question is here.
So to answer your question:
--add-drop-database
option in your mysqldump
statement.--databases
or --all-databases
and the CREATE DATABASE
syntax will be added
automaticallyMore information at MySQL Reference Manual
Use document.querySelector() if you want to avoid frameworks (which I almost always want to do).
document.querySelector('input[name="gender"]:checked').value
int rowscount = dataGridView1.Rows.Count;
for (int i = 0; i < rowscount; i++)
{
if (!(dataGridView1.Rows[i].Cells[8].Value == null))
{
dataGridView1.Rows[i].Cells[8].Style.BackColor = Color.LightGoldenrodYellow;
}
}
If you do not want to attach code in a file (this was a good tip, ChssPly76, I need to check it out), you can try changing the default message format messages to rich text (Tools - Options - Mail Format - Message format) instead of HTML. I learned that Outlook's HTML formatting screws code layout (btw, Outlook uses MS Word's HTML rendering engine which sucks big time), but rich text works fine. So if I copy code from Visual Studio and paste it in Outlook message, when using rich text, it looks pretty good, but when in HTML mode, it's a disaster. To disable smart quotes, auto-correction, and other artifacts, set up the appropriate option via Tools - Options - Spelling - Spelling and AutoCorrection; you may also want to play with copy-paste settings (Tools - Options - Mail Format - Editor Options - Cut, copy, and paste).
Seems like var ctx = $('#myChart');
is returning a list of elements. You would need to reference the first by using ctx[0]
.
Also height is a property, not a function.
I did it this way in my code:
var ctx = document.getElementById("myChart");
ctx.height = 500;
WARNING: slaveOk() is deprecated and may be removed in the next major release. Please use secondaryOk() instead. rs.secondaryOk()
DateTime.Now.ToString("yyyy-MM-dd h:mm:ss tt");
just Try It's use full to your Need
Another difference between a bare and non-bare repository is that a bare repository does not have a default remote origin repository:
~/Projects$ git clone --bare test bare
Initialized empty Git repository in /home/derek/Projects/bare/
~/Projects$ cd bare
~/Projects/bare$ git branch -a
* master
~/Projects/bare$ cd ..
~/Projects$ git clone test non-bare
Initialized empty Git repository in /home/derek/Projects/non-bare/.git/
~/Projects$ cd non-bare
~/Projects/non-bare$ git branch -a
* master
remotes/origin/HEAD -> origin/master
remotes/origin/master
From the manual page for git clone --bare
:
Also the branch heads at the remote are copied directly to corresponding local branch heads, without mapping them to refs/remotes/origin/. When this option is used, neither remote-tracking branches nor the related configuration variables are created.
Presumably, when it creates a bare repository, Git assumes that the bare repository will serve as the origin repository for several remote users, so it does not create the default remote origin. What this means is that basic git pull
and git push
operations won't work since Git assumes that without a workspace, you don't intend to commit any changes to the bare repository:
~/Projects/bare$ git push
fatal: No destination configured to push to.
~/Projects/bare$ git pull
fatal: /usr/lib/git-core/git-pull cannot be used without a working tree.
~/Projects/bare$
You don't need the executable for setuptools.
You can download the source code, unpack it, traverse to the downloaded directory and run python setup.py install
in the command prompt
According to the documentation AnimationSet
Represents a group of Animations that should be played together. The transformation of each individual animation are composed together into a single transform. If AnimationSet sets any properties that its children also set (for example, duration or fillBefore), the values of AnimationSet override the child values
AnimationSet mAnimationSet = new AnimationSet(false); //false means don't share interpolators
Pass true if all of the animations in this set should use the interpolator associated with this AnimationSet. Pass false if each animation should use its own interpolator.
ImageView imageView= (ImageView)findViewById(R.id.imageView);
Animation fadeInAnimation = AnimationUtils.loadAnimation(this, R.anim.fade_in);
Animation fadeOutAnimation = AnimationUtils.loadAnimation(this, R.anim.fade_out);
mAnimationSet.addAnimation(fadeInAnimation);
mAnimationSet.addAnimation(fadeOutAnimation);
imageView.startAnimation(mAnimationSet);
I hope this will help you.
editTxt.setOnFocusChangeListener { v, hasFocus ->
val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
if (hasFocus) {
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY)
} else {
imm.hideSoftInputFromWindow(v.windowToken, 0)
}
}
That is really important for example when you are writing a network analyzer. packet headers are defined by the protocol specification, not by the way a particular platform's C compiler works.
if you are a sudo user i mean if you got sudo access:
sudo sh startup.sh
otherwise: sh startup.sh
But things is that you have to be on the bin directory of your server like
cd /home/nanofaroque/servers/apache-tomcat-7.0.47/bin
In case you want to utilize .then() which has a subtle difference in comparison with .done() :
return $.post(url, payload)
.then(
function (result, textStatus, jqXHR) {
return result;
},
function (jqXHR, textStatus, errorThrown) {
return console.error(errorThrown);
});
You can write a very elegant solution using a functional style.
class Object
def hashify
Hash[instance_variables.map { |v| [v.to_s[1..-1].to_sym, instance_variable_get v] }]
end
end
Create Common Method to Convert String to Date format
public static void main(String[] args) throws Exception {
long test = ConvertStringToDate("May 26 10:41:23", "MMM dd hh:mm:ss");
long test2 = ConvertStringToDate("Tue, Jun 06 2017, 12:30 AM", "EEE, MMM dd yyyy, hh:mm a");
long test3 = ConvertStringToDate("Jun 13 2003 23:11:52.454 UTC", "MMM dd yyyy HH:mm:ss.SSS zzz");
}
private static long ConvertStringToDate(String dateString, String format) {
try {
return new SimpleDateFormat(format).parse(dateString).getTime();
} catch (ParseException e) {}
return 0;
}
Some JavaScript engines can parse that format directly, which makes the task pretty easy:
function convertDate(inputFormat) {_x000D_
function pad(s) { return (s < 10) ? '0' + s : s; }_x000D_
var d = new Date(inputFormat)_x000D_
return [pad(d.getDate()), pad(d.getMonth()+1), d.getFullYear()].join('/')_x000D_
}_x000D_
_x000D_
console.log(convertDate('Mon Nov 19 13:29:40 2012')) // => "19/11/2012"
_x000D_
Mutex in essence is a lock, providing protected access to shared resources. Under Linux, the thread mutex data type is pthread_mutex_t. Before use, initialize it.
To access to shared resources, you have to lock on the mutex. If the mutex already on the lock, the call will block the thread until the mutex is unlocked. Upon completion of the visit to shared resources, you have to unlock them.
Overall, there are a few unwritten basic principles:
Obtain the lock before using the shared resources.
Holding the lock as short time as possible.
Release the lock if the thread returns an error.
On API 22 The Use Of BasicNamevalue Pair is depricated, instead use the HASMAP for that. To know more about the HasMap visit here more on hasmap developer.android
package com.yubraj.sample.datamanager;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import com.yubaraj.sample.utilities.GeneralUtilities;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import javax.net.ssl.HttpsURLConnection;
/**
* Created by yubraj on 7/30/15.
*/
public class ServerRequestHandler {
private static final String TAG = "Server Request";
OnServerRequestComplete listener;
public ServerRequestHandler (){
}
public void doServerRequest(HashMap<String, String> parameters, String url, int requestType, OnServerRequestComplete listener){
debug("ServerRequest", "server request called, url = " + url);
if(listener != null){
this.listener = listener;
}
try {
new BackgroundDataSync(getPostDataString(parameters), url, requestType).execute();
debug(TAG , " asnyc task called");
} catch (Exception e) {
e.printStackTrace();
}
}
public void doServerRequest(HashMap<String, String> parameters, String url, int requestType){
doServerRequest(parameters, url, requestType, null);
}
public interface OnServerRequestComplete{
void onSucess(Bundle bundle);
void onFailed(int status_code, String mesage, String url);
}
public void setOnServerRequestCompleteListener(OnServerRequestComplete listener){
this.listener = listener;
}
private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for(Map.Entry<String, String> entry : params.entrySet()){
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return result.toString();
}
class BackgroundDataSync extends AsyncTask<String, Void , String>{
String params;
String mUrl;
int request_type;
public BackgroundDataSync(String params, String url, int request_type){
this.mUrl = url;
this.params = params;
this.request_type = request_type;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected String doInBackground(String... urls) {
debug(TAG, "in Background, urls = " + urls.length);
HttpURLConnection connection;
debug(TAG, "in Background, url = " + mUrl);
String response = "";
switch (request_type) {
case 1:
try {
connection = iniitializeHTTPConnection(mUrl, "POST");
OutputStream os = connection.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(params);
writer.flush();
writer.close();
os.close();
int responseCode = connection.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
/* String line;
BufferedReader br=new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((line=br.readLine()) != null) {
response+=line;
}*/
response = getDataFromInputStream(new InputStreamReader(connection.getInputStream()));
} else {
response = "";
}
} catch (IOException e) {
e.printStackTrace();
}
break;
case 0:
connection = iniitializeHTTPConnection(mUrl, "GET");
try {
if (connection.getResponseCode() == connection.HTTP_OK) {
response = getDataFromInputStream(new InputStreamReader(connection.getInputStream()));
}
} catch (Exception e) {
e.printStackTrace();
response = "";
}
break;
}
return response;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if(TextUtils.isEmpty(s) || s.length() == 0){
listener.onFailed(DbConstants.NOT_FOUND, "Data not found", mUrl);
}
else{
Bundle bundle = new Bundle();
bundle.putInt(DbConstants.STATUS_CODE, DbConstants.HTTP_OK);
bundle.putString(DbConstants.RESPONSE, s);
bundle.putString(DbConstants.URL, mUrl);
listener.onSucess(bundle);
}
//System.out.println("Data Obtained = " + s);
}
private HttpURLConnection iniitializeHTTPConnection(String url, String requestType) {
try {
debug("ServerRequest", "url = " + url + "requestType = " + requestType);
URL link = new URL(url);
HttpURLConnection conn = (HttpURLConnection) link.openConnection();
conn.setRequestMethod(requestType);
conn.setDoInput(true);
conn.setDoOutput(true);
return conn;
}
catch(Exception e){
e.printStackTrace();
}
return null;
}
}
private String getDataFromInputStream(InputStreamReader reader){
String line;
String response = "";
try {
BufferedReader br = new BufferedReader(reader);
while ((line = br.readLine()) != null) {
response += line;
debug("ServerRequest", "response length = " + response.length());
}
}
catch (Exception e){
e.printStackTrace();
}
return response;
}
private void debug(String tag, String string) {
Log.d(tag, string);
}
}
and Just call the function when you needed to get the data from server either by post or get like this
HashMap<String, String>params = new HashMap<String, String>();
params.put("action", "request_sample");
params.put("name", uname);
params.put("message", umsg);
params.put("email", getEmailofUser());
params.put("type", "bio");
dq.doServerRequest(params, "your_url", DbConstants.METHOD_POST);
dq.setOnServerRequestCompleteListener(new ServerRequestHandler.OnServerRequestComplete() {
@Override
public void onSucess(Bundle bundle) {
debug("data", bundle.getString(DbConstants.RESPONSE));
}
@Override
public void onFailed(int status_code, String mesage, String url) {
debug("sample", mesage);
}
});
Now it is complete.Enjoy!!! Comment it if find any problem.
php have a easy way to run a light server:
first cd into php file directory, then
php -S 127.0.0.1:8000
then you can run php
Single-source Python 2/3 compatible version based on @pts' answer:
#!/usr/bin/env python
import binascii
def int2bytes(i):
hex_string = '%x' % i
n = len(hex_string)
return binascii.unhexlify(hex_string.zfill(n + (n & 1)))
print(int2bytes(1245427))
# -> b'\x13\x00\xf3'
axis([xmin, xmax, ymin, ymax])
So you could add something like this at the end:
plt.axis([min(x_arr), max(x_arr), max(y_arr), 0])
Although you might want padding at each end so that the extreme points don't sit on the border.
It is not good practice to hard code strings into your layout files. You should add them to a string resource file and then reference them from your layout.
This allows you to update every occurrence of the word "Yellow" in all layouts at the same time by just editing your strings.xml file.
It is also extremely useful for supporting multiple languages as a separate strings.xml file can be used for each supported language.
example: XML file saved at res/values/strings.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="yellow">Yellow</string>
</resources>
This layout XML applies a string to a View:
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/yellow" />
Similarly colors should be stored in colors.xml and then referenced by using @color/color_name
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="Black">#000000</color>
</resources>
Console.WriteLine(curr.ToString("HH:mm"));
Use Window Object
window.console.log("..")
new[] { ',', '.', ';', '\'', '@' }
.Aggregate("My name @is ,Wan.;'; Wan", (s, c) => s.Replace(c.ToString(), string.Empty));
Acknowledging this as an older post but still figured I'd add this suggestion to the list of responses since I hadn't seen it mentioned.
If the unresolved reference exists within context of another Project in the Solution:
Right-click the Project having the problem, select Build Dependencies --> Project Dependencies and ensure the desired Project is selected for reference.
I had the same issue as described in the post however none of the suggested manners for resolution worked. I'd never seen such a quirk in VS before (running VS 2019 at present)
I checked for potential namespace issues and a plethora of the more obvious causes and nothing made sense. Intellisense even acknowledged the existence of the other Project and suggested to a the using statement but even after having added the using reference; VS 2019 still wouldn't acknowledge the other project.
Forcing the dependency in the manner described resolved the issue.
Almost there. In your predicate, you want a relative path, so change
./book[/author/name = 'John']
to either
./book[author/name = 'John']
or
./book[./author/name = 'John']
and you will match your element. Your current predicate goes back to the root of the document to look for an author
.
Since this is one of the top search results for questions related to this I felt it was worth mentioning how you can make this work with Kendo().DropDownListFor() as well.
Everything is the same as with OnaBai's post except for how you select the item based off of its text and your selector.
To do that you would swap out dataItem.symbol for dataItem.[DataTextFieldName]. Whatever model field you used for .DataTextField() is what you will be comparing against.
@(Html.Kendo().DropDownListFor(model => model.Status.StatusId)
.Name("Status.StatusId")
.DataTextField("StatusName")
.DataValueField("StatusId")
.BindTo(...)
)
//So that your ViewModel gets bound properly on the post, naming is a bit
//different and as such you need to replace the periods with underscores
var ddl = $('#Status_StatusId').data('kendoDropDownList');
ddl.select(function(dataItem) {
return dataItem.StatusName === "Active";
});
This happens when your maven project uses different Compiler Compliance level and Eclipse IDE uses different Compiler Compliance level. In order to fix this we need to change the Compiler Compliance level of Maven project to the level IDE uses.
1) To See Java Compiler Compliance level uses in Eclipse IDE
*) Window -> Preferences -> Compiler -> Compiler Compliance level : 1.8 (or 1.7, 1.6 ,, ect)
2) To Change Java Compiler Compliance level of Maven project
*) Go to "Project" -> "Properties" -> Select "Java Compiler" -> Change the Compiler Compliance level : 1.8 (or 1.7, 1.6 ,, ect)
square = function(a) {
if ((a * 0) == 0) {
return a*a;
} else {
return "Enter a valid number.";
}
}
I found this method the easiest:
$start_date = '2009-06-17';
$end_date = '2009-09-05';
$date_from_user = '2009-08-28';
$start_date = date_create($start_date);
$date_from_user = date_create($date_from_user);
$end_date = date_create($end_date);
$interval1 = date_diff($start_date, $date_from_user);
$interval2 = date_diff($end_date, $date_from_user);
if($interval1->invert == 0){
if($interval2->invert == 1){
// if it lies between start date and end date execute this code
}
}
From what I know, it's highly recommended NOT to use the Finalizer / Destructor:
public ~MyClass() {
//dont use this
}
Mostly, this is due to not knowing when or IF it will be called. The dispose method is much better, especially if you us using or dispose directly.
using is good. use it :)
I usually use
<?php echo get_current_user(); ?>
I will be glad if it helped you
You can wrap the inputs in col-*
classes
<form name="registration_form" id="registration_form" class="form-horizontal">
<div class="form-group">
<div class="col-sm-6">
<label for="firstname" class="sr-only"></label>
<input id="firstname" class="form-control input-group-lg reg_name" type="text" name="firstname" title="Enter first name" placeholder="First name">
</div>
<div class="col-sm-6">
<label for="lastname" class="sr-only"></label>
<input id="lastname" class="form-control input-group-lg reg_name" type="text" name="lastname" title="Enter last name" placeholder="Last name">
</div>
</div><!--/form-group-->
<div class="form-group">
<div class="col-sm-12">
<label for="username" class="sr-only"></label>
<input id="username" class="form-control input-group-lg" type="text" autocapitalize="off" name="username" title="Enter username" placeholder="Username">
</div>
</div><!--/form-group-->
<div class="form-group">
<div class="col-sm-12">
<label for="password" class="sr-only"></label>
<input id="password" class="form-control input-group-lg" type="password" name="password" title="Enter password" placeholder="Password">
</div>
</div><!--/form-group-->
</form>
TO ADD: @Christopher's answer does not work on API 7/8 (as per @Jonny's correct comment) IF you are using colours, instead of drawables. (In my testing, using drawables as per Christopher works fine)
Here is the FIX for 2.3 and below when using colours:
As per @Charles Harley, there is a bug in 2.3 and below where filling the list item with a colour causes the colour to flow out over the whole list. His fix is to define a shape
drawable containing the colour you want, and to use that instead of the colour.
I suggest looking at this link if you want to just use a colour as selector, and are targeting Android 2 (or at least allow for Android 2).
Following these reccomended directions seemed to work:
Hint: Open the SDK manager by running: /path/to/android/tools/android
You will require: 1. "SDK Platform" for android-23 2. "Android SDK Platform-tools (latest) 3. "Android SDK Build-tools" (latest)
another way is to create a table
with valign
, of course. This would work regardless of you knowing the div's height or not.
<div>
<table width="100%" height="100%" align="center" valign="center">
<tr><td>
<img src="foo.jpg" alt="foo" />
</td></tr>
</table>
</div>
but you should always stick to just css
whenever possible.
Use a list instead and replace your foreach
loop with a for
loop:
@model IList<BlockedIPViewModel>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@for (var i = 0; i < Model.Count; i++)
{
<tr>
<td>
@Html.HiddenFor(x => x[i].IP)
@Html.CheckBoxFor(x => x[i].Checked)
</td>
<td>
@Html.DisplayFor(x => x[i].IP)
</td>
</tr>
}
<div>
<input type="submit" value="Unblock IPs" />
</div>
}
Alternatively you could use an editor template:
@model IEnumerable<BlockedIPViewModel>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.EditorForModel()
<div>
<input type="submit" value="Unblock IPs" />
</div>
}
and then define the template ~/Views/Shared/EditorTemplates/BlockedIPViewModel.cshtml
which will automatically be rendered for each element of the collection:
@model BlockedIPViewModel
<tr>
<td>
@Html.HiddenFor(x => x.IP)
@Html.CheckBoxFor(x => x.Checked)
</td>
<td>
@Html.DisplayFor(x => x.IP)
</td>
</tr>
The reason you were getting null in your controller is because you didn't respect the naming convention for your input fields that the default model binder expects to successfully bind to a list. I invite you to read the following article
.
Once you have read it, look at the generated HTML (and more specifically the names of the input fields) with my example and yours. Then compare and you will understand why yours doesn't work.
There are lots of answers, but none explained nicely what else can be done. Looking into man pages for dd, it is possible to better specify the size of a file.
This is going to create /tmp/zero_big_data_file.bin filled with zeros, that has size of 20 megabytes :
dd if=/dev/zero of=/tmp/zero_big_data_file.bin bs=1M count=20
This is going to create /tmp/zero_1000bytes_data_file.bin filled with zeros, that has size of 1000 bytes :
dd if=/dev/zero of=/tmp/zero_1000bytes_data_file.bin bs=1kB count=1
or
dd if=/dev/zero of=/tmp/zero_1000bytes_data_file.bin bs=1000 count=1
If you are doing development in Java 8 and Hibernate 5 Or Spring Boot JPA then use following annotation directly in your Entity class. Hibernate gets the current timestamp from the VM and will insert date and time in database.
public class YourEntity {
@Id
@GeneratedValue
private Long id;
private String name;
@CreationTimestamp
private LocalDateTime createdDateTime;
@UpdateTimestamp
private LocalDateTime updatedDateTime;
…
}
preg_match('/(?:http[s]*\:\/\/)*(.*?)\.(?=[^\/]*\..{2,5})/i', $url, $match);
Just read $match[1]
It works perfectly with this list of urls
$url = array(
'http://www.domain.com', // www
'http://domain.com', // --nothing--
'https://domain.com', // --nothing--
'www.domain.com', // www
'domain.com', // --nothing--
'www.domain.com/some/path', // www
'http://sub.domain.com/domain.com', // sub
'???????????????.????????.ua', // ??????????????? ;)
'????????.ua', // --nothing--
'http://sub-domain.domain.net/domain.net', // sub-domain
'sub-domain.third-Level_DomaIN.domain.uk.co/domain.net' // sub-domain
);
foreach ($url as $u) {
preg_match('/(?:http[s]*\:\/\/)*(.*?)\.(?=[^\/]*\..{2,5})/i', $u, $match);
var_dump($match);
}
Where is this info kept ("this connection is between computer
A
and serverF
")?
A TCP connection is recognized by source IP and port and destination IP and port. Your OS, all intermediate session-aware devices and the server's OS will recognize the connection by this.
HTTP works with request-response: client connects to server, performs a request and gets a response. Without keep-alive, the connection to an HTTP server is closed after each response. With HTTP keep-alive you keep the underlying TCP connection open until certain criteria are met.
This allows for multiple request-response pairs over a single TCP connection, eliminating some of TCP's relatively slow connection startup.
When The IIS (F) sends keep alive header (or user sends keep-alive) , does it mean that (E,C,B) save a connection
No. Routers don't need to remember sessions. In fact, multiple TCP packets belonging to same TCP session need not all go through same routers - that is for TCP to manage. Routers just choose the best IP path and forward packets. Keep-alive is only for client, server and any other intermediate session-aware devices.
which is only for my session ?
Does it mean that no one else can use that connection
That is the intention of TCP connections: it is an end-to-end connection intended for only those two parties.
If so - does it mean that keep alive-header - reduce the number of overlapped connection users ?
Define "overlapped connections". See HTTP persistent connection for some advantages and disadvantages, such as:
if so , for how long does the connection is saved to me ? (in other words , if I set keep alive- "keep" till when?)
An typical keep-alive response looks like this:
Keep-Alive: timeout=15, max=100
See Hypertext Transfer Protocol (HTTP) Keep-Alive Header for example (a draft for HTTP/2 where the keep-alive header is explained in greater detail than both 2616 and 2086):
A host sets the value of the timeout
parameter to the time that the host will allows an idle connection to remain open before it is closed. A connection is idle if no data is sent or received by a host.
The max
parameter indicates the maximum number of requests that a client will make, or that a server will allow to be made on the persistent connection. Once the specified number of requests and responses have been sent, the host that included the parameter could close the connection.
However, the server is free to close the connection after an arbitrary time or number of requests (just as long as it returns the response to the current request). How this is implemented depends on your HTTP server.
There's always LINQ:
t.GetProperties().Where(
p=>p.GetCustomAttributes(typeof(MyAttribute), true).Length != 0)
Apply this if you use laravel.
Laravel has a not_regex where field under validation must not match the given regular expression; uses the PHP preg_match
function internally.
'email' => 'not_regex:/^.+$/i'
This is also useful if you only want to temporarily suppress the warning:
import matplotlib.pyplot as plt
with plt.rc_context(rc={'figure.max_open_warning': 0}):
lots_of_plots()
Yet another possible cause:
In my case, I had a xib
and was calling Bundle.main.loadNibNamed(...
at which point it was crashing. All my IBOutlets
and IBActions
seemed fine. In the end I noticed that the nib
was actually loading, but then when I tried to access the first (and only) view (nib.first
), that was not working. In fact nib.count
was returning a very large integer (max int?), instead of the expected 1
. I tried re-adding the view, but still no luck.
In the end, I deleted the whole xib
file and started again (but I kept some of the views in my clipboard so I can paste them instead of recreating them again).
This worked!
If you are using the 'pylab' for interactive plotting you can set the labelsize at creation time with pylab.ylabel('Example', fontsize=40)
.
If you use pyplot
programmatically you can either set the fontsize on creation with ax.set_ylabel('Example', fontsize=40)
or afterwards with ax.yaxis.label.set_size(40)
.
I know this answer is not directly related to this questions' issue but in some cases the "Uncaught ReferenceError: google is not defined" issue will occur if your js file is being called prior to the google maps api you're using...so DON'T DO this:
<script type ="text/javascript" src ="SomeJScriptfile.js"></script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
I believe this will work:
TextArea.Text = "Line 1" & vbCrLf & "Line 2"
System.Environment.NewLine could be used in place of vbCrLf if you wanted to be a little less VB6 about it.