/(?:(?!</s\w)<[^<])</s\w*/gi; - Removes any sequence in any combination with
Without doing this %config IPCompleter.greedy=True
after you import a package like numpy or pandas in this way;
import numpy as np
import pandas as pd
.
Then you type in pd.
then tap the tab button it brings out all the possible methods to use very easy and straight forward.
Why not just convert all <button>
to <span>
with type="button"
and then style with your normal css button classes? Just confirmed that this works in IE11.
From the Java Tutorial:
Nested classes are divided into two categories: static and non-static. Nested classes that are declared static are simply called static nested classes. Non-static nested classes are called inner classes.
Static nested classes are accessed using the enclosing class name:
OuterClass.StaticNestedClass
For example, to create an object for the static nested class, use this syntax:
OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();
Objects that are instances of an inner class exist within an instance of the outer class. Consider the following classes:
class OuterClass {
...
class InnerClass {
...
}
}
An instance of InnerClass can exist only within an instance of OuterClass and has direct access to the methods and fields of its enclosing instance.
To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax:
OuterClass outerObject = new OuterClass()
OuterClass.InnerClass innerObject = outerObject.new InnerClass();
see: Java Tutorial - Nested Classes
For completeness note that there is also such a thing as an inner class without an enclosing instance:
class A {
int t() { return 1; }
static A a = new A() { int t() { return 2; } };
}
Here, new A() { ... }
is an inner class defined in a static context and does not have an enclosing instance.
Or, for less code, inside your click you place:
setTimeout(function(){
$('#DIV_ID').scrollTop(0);
}, 500);
Same thing you'd expect from normal modulo .. e.g. 7 % 4 = 3
, 7.3 % 4.0 = 3.3
Beware of floating point accuracy issues.
Use a comma ","
eg:
UPDATE my_table SET rowOneValue = rowOneValue + 1, rowTwoValue = rowTwoValue + ( (rowTwoValue / (rowTwoValue) ) + ?) * (v + 1) WHERE value = ?
I modified Flood's script to execute once for each table rather than for every column of each table for faster execution. It requires Oracle 11g or greater.
set serveroutput on size 100000
declare
v_match_count integer;
v_counter integer;
-- The owner of the tables to search through (case-sensitive)
v_owner varchar2(255) := 'OWNER_NAME';
-- A string that is part of the data type(s) of the columns to search through (case-insensitive)
v_data_type varchar2(255) := 'CHAR';
-- The string to be searched for (case-insensitive)
v_search_string varchar2(4000) := 'FIND_ME';
-- Store the SQL to execute for each table in a CLOB to get around the 32767 byte max size for a VARCHAR2 in PL/SQL
v_sql clob := '';
begin
for cur_tables in (select owner, table_name from all_tables where owner = v_owner and table_name in
(select table_name from all_tab_columns where owner = all_tables.owner and data_type like '%' || upper(v_data_type) || '%')
order by table_name) loop
v_counter := 0;
v_sql := '';
for cur_columns in (select column_name from all_tab_columns where
owner = v_owner and table_name = cur_tables.table_name and data_type like '%' || upper(v_data_type) || '%') loop
if v_counter > 0 then
v_sql := v_sql || ' or ';
end if;
v_sql := v_sql || 'upper(' || cur_columns.column_name || ') like ''%' || upper(v_search_string) || '%''';
v_counter := v_counter + 1;
end loop;
v_sql := 'select count(*) from ' || cur_tables.table_name || ' where ' || v_sql;
execute immediate v_sql
into v_match_count;
if v_match_count > 0 then
dbms_output.put_line('Match in ' || cur_tables.owner || ': ' || cur_tables.table_name || ' - ' || v_match_count || ' records');
end if;
end loop;
exception
when others then
dbms_output.put_line('Error when executing the following: ' || dbms_lob.substr(v_sql, 32600));
end;
/
Gradle 6.3, Java library. The code from "jar task" adds the dependencies to the "build/libs/xyz.jar" when running "gradle build" task.
plugins {
id 'java-library'
}
jar {
from {
configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }
}
}
To find all files modified in the last 24 hours use the one below. The -1 here means changed 1 day or less ago.
find . -mtime -1 -ls
For Ansible 2.x:
- name: template test
template:
src: myTemplateFile
dest: result1
vars:
myTemplateVariable: File1
- name: template test
template:
src: myTemplateFile
dest: result2
vars:
myTemplateVariable: File2
For Ansible 1.x:
Unfortunately the template
module does not support passing variables to it, which can be used inside the template. There was a feature request but it was rejected.
I can think of two workarounds:
1. Include
The include
statement supports passing variables. So you could have your template
task inside an extra file and include it twice with appropriate parameters:
my_include.yml:
- name: template test
template:
src=myTemplateFile
dest=destination
main.yml:
- include: my_include.yml destination=result1 myTemplateVariable=File1
- include: my_include.yml destination=result2 myTemplateVariable=File2
2. Re-define myTemplateVariable
Another way would be to simply re-define myTemplateVariable right before every template
task.
- set_fact:
myTemplateVariable: File1
- name: template test 1
template:
src=myTemplateFile
dest=result1
- set_fact:
myTemplateVariable: File2
- name: template test 2
template:
src=myTemplateFile
dest=result2
I got the way to redirect the out put to console as well as to a text file as well simultaneously:
te = open('log.txt','w') # File where you need to keep the logs
class Unbuffered:
def __init__(self, stream):
self.stream = stream
def write(self, data):
self.stream.write(data)
self.stream.flush()
te.write(data) # Write the data of stdout here to a text file as well
sys.stdout=Unbuffered(sys.stdout)
You can use the lower
function:
Guide.where("lower(title)='attack'")
As a comment: Work on your question. The title isn't terribly informative, and you drop a big chunk of code at the end that is irrelevant to your question.
Im my case I added and id equals to the name automatically generated for VS on the html and in the code I´ve added a line to that case.
$(function () {
$.validator.addMethod('latinos', function (value, element) {
return this.optional(element) || /^[a-záéóóúàèìòùäëïöüñ\s]+$/i.test(value);
});
$("#btn").on("click", function () {
//alert("aa");
$("#formulario").validate({
rules:
{
email: { required: true, email: true, minlength: 8, maxlength: 80 },
digitos: { required: true, digits: true, minlength: 2, maxlength: 100 },
nombres: { required: true, latinos: true, minlength: 3, maxlength: 50 },
NombresUsuario: { required: true, latinos: true, minlength: 3, maxlength: 50 }
},
messages:
{
email: {
required: 'El campo es requerido', email: 'El formato de email es incorrecto',
minlength: 'El mínimo permitido es 8 caracteres', maxlength: 'El máximo permitido son 80 caracteres'
},
digitos: {
required: 'El campo es requerido', digits: 'Sólo se aceptan dígitos',
minlength: 'El mínimo permitido es 2 caracteres', maxlength: 'El máximo permitido son 10 caracteres'
},
nombres: {
required: 'El campo es requerido', latinos: 'Sólo se aceptan letras',
minlength: 'El mínimo permitido es 3 caracteres', maxlength: 'El máximo permitido son 50 caracteres'
},
NombresUsuario: {
required: 'El campo es requerido', latinos: 'Sólo se aceptan letras',
minlength: 'El mínimo permitido es 3 caracteres', maxlength: 'El máximo permitido son 50 caracteres'
}
}
});
});
<tr>@*<div class="form-group"> htmlAttributes: new { @class = "control-label col-md-2" } , @class = "form-control" }*@
<td>@Html.LabelFor(model => model.NombresUsuario )</td>
@*<div class="col-md-10">*@
<td>
@Html.EditorFor(model => model.NombresUsuario, new { htmlAttributes = new { id = "NombresUsuario" } })
@Html.ValidationMessageFor(model => model.NombresUsuario, "", new { @class = "text-danger" })
</td>
You can use "wildcards" with MATCH
so assuming "ASDFGHJK" in H1 as per Peter's reply you can use this regular formula
=INDEX(G:G,MATCH("*"&H1&"*",G:G,0)+3)
MATCH can only reference a single column or row so if you want to search 6 columns you either have to set up a formula with 6 MATCH functions or change to another approach - try this "array formula", assuming search data in A2:G100
=INDIRECT("R"&REPLACE(TEXT(MIN(IF(ISNUMBER(SEARCH(H1,A2:G100)),(ROW(A2:G100)+3)*1000+COLUMN(A2:G100))),"000000"),4,0,"C"),FALSE)
confirmed with Ctrl-Shift-Enter
Clearly a Cell cannot contain another cell as it becomes a never-ending recursion.
However a Cell CAN contain a pointer to another cell.
typedef struct Cell {
bool isParent;
struct Cell* child;
} Cell;
Your variable size
is declared as: float size;
You can't use a floating point variable as the size of an array - it needs to be an integer value.
You could cast it to convert to an integer:
float *temp = new float[(int)size];
Your other problem is likely because you're writing outside of the bounds of the array:
float *temp = new float[size];
//Getting input from the user
for (int x = 1; x <= size; x++){
cout << "Enter temperature " << x << ": ";
// cin >> temp[x];
// This should be:
cin >> temp[x - 1];
}
Arrays are zero based in C++, so this is going to write beyond the end and never write the first element in your original code.
To add to the other answers, you can also exit a method by throwing an exception manually:
throw new Exception();
I am having quite a lot of luck with tesseract-android-tools
winpty works as long as you don't specify volumes to be mounted such as ".:/mountpoint" or "${pwd}:/mountpoint"
The best workaround I have found is to use the git-bash plugin inside Visual Code Studio and use the terminal to start and stop containers or docker-compose.
Static method never allows a non-static method call directly.
Reason: Static method belongs to its class only, and to nay object or any instance.
So, whenever you try to access any non-static method from static method inside the same class: you will receive:
"An object reference is required for the non-static field, method or property".
Solution: Just declare a reference like:
public class <classname>
{
static method()
{
new <classname>.non-static();
}
non-static method()
{
}
}
You need to reference both Microsoft.ReportViewer.WebForms and Microsoft.ReportViewer.Common and set the CopyLocal property to true. This will result in the dll's being copied to our bin directory (both are necessary).
I found this question through another question which was KeystoneJS specific but was marked as duplicate. If anyone here might be looking for a Keystone answer, this is how I did my deep populate query in Keystone.
Mongoose two level population using KeystoneJs [duplicate]
exports.getStoreWithId = function (req, res) {
Store.model
.find()
.populate({
path: 'productTags productCategories',
populate: {
path: 'tags',
},
})
.where('updateId', req.params.id)
.exec(function (err, item) {
if (err) return res.apiError('database error', err);
// possibly more than one
res.apiResponse({
store: item,
});
});
};
You can use the opt(int)
method and use a classical for
loop.
Dim
and Private
work the same, though the common convention is to use Private
at the module level, and Dim
at the Sub/Function level. Public
and Global
are nearly identical in their function, however Global
can only be used in standard modules, whereas Public
can be used in all contexts (modules, classes, controls, forms etc.) Global
comes from older versions of VB and was likely kept for backwards compatibility, but has been wholly superseded by Public
.
The token has to be placed in an Authorization header according to the following format:
Authorization: Bearer [Token_Value]
import urllib2
import json
def get_auth_token():
"""
get an auth token
"""
req=urllib2.Request("https://xforce-api.mybluemix.net/auth/anonymousToken")
response=urllib2.urlopen(req)
html=response.read()
json_obj=json.loads(html)
token_string=json_obj["token"].encode("ascii","ignore")
return token_string
def get_response_json_object(url, auth_token):
"""
returns json object with info
"""
auth_token=get_auth_token()
req=urllib2.Request(url, None, {"Authorization": "Bearer %s" %auth_token})
response=urllib2.urlopen(req)
html=response.read()
json_obj=json.loads(html)
return json_obj
Not enough reputation to comment yet so I'll just put this here:
To expand on Micah's answer - the browser runs your code top to bottom, so if you write:
<div id="chart"></div>
<script>var svg = d3.select("#chart").append("svg:svg");</script>
The browser will create a div with id "chart", and then run your script, which will try to find that div, and, hurray, success.
Otherwise if you write:
<script>var svg = d3.select("#chart").append("svg:svg");</script>
<div id="chart"></div>
The browser runs your script, and tries to find a div with id chart, but it hasn't been created yet so it fails.
THEN the browser creates a div with id "chart".
You can use:
Class.forName(String).getConstructor(arguments types).newInstance(arguments)
But you need to supply the exact class name, including packages, eg. java.io.FileInputStream
. I used this to create a math expressions parser.
On 14th of April (2015), npm private modules were introduced.
When you pay for private modules, you can:
- Host as many private packages as you want
- Give read access or read-write access for those packages to any other paid user
- Install and use any packages that other paid users have given you read access to
- Collaborate on any packages that other paid users have given you write access to
Of course it's not free - currently 7$ a month, per user.
And it's still a pretty new service. For example support for organization accounts is missing (as of June 2015):
Currently, private packages are only available for individual users, but support for organization accounts is coming soon. Feel free to create a user for your organization in the meantime, and we can upgrade it to an organization when support is here.
So while not perfect, it's the official npm solution to maintaining private packages, and that itself makes it worth mentioning.
UPDATE
Npm Private Packages are now available, with plans for both individual users and organizations:
- Unlimited number of public & private packages
- $7/month/developer
- Includes one scope name, based on organization name
- Publish and control access to @org-name/foo
(disclaimer: not even remotely affiliated in any way with npm, Inc.)
Just use readLines
on your file:
R> res <- readLines(system.file("DESCRIPTION", package="MASS"))
R> length(res)
[1] 27
R> res
[1] "Package: MASS"
[2] "Priority: recommended"
[3] "Version: 7.3-18"
[4] "Date: 2012-05-28"
[5] "Revision: $Rev: 3167 $"
[6] "Depends: R (>= 2.14.0), grDevices, graphics, stats, utils"
[7] "Suggests: lattice, nlme, nnet, survival"
[8] "Authors@R: c(person(\"Brian\", \"Ripley\", role = c(\"aut\", \"cre\", \"cph\"),"
[9] " email = \"[email protected]\"), person(\"Kurt\", \"Hornik\", role"
[10] " = \"trl\", comment = \"partial port ca 1998\"), person(\"Albrecht\","
[11] " \"Gebhardt\", role = \"trl\", comment = \"partial port ca 1998\"),"
[12] " person(\"David\", \"Firth\", role = \"ctb\"))"
[13] "Description: Functions and datasets to support Venables and Ripley,"
[14] " 'Modern Applied Statistics with S' (4th edition, 2002)."
[15] "Title: Support Functions and Datasets for Venables and Ripley's MASS"
[16] "License: GPL-2 | GPL-3"
[17] "URL: http://www.stats.ox.ac.uk/pub/MASS4/"
[18] "LazyData: yes"
[19] "Packaged: 2012-05-28 08:47:38 UTC; ripley"
[20] "Author: Brian Ripley [aut, cre, cph], Kurt Hornik [trl] (partial port"
[21] " ca 1998), Albrecht Gebhardt [trl] (partial port ca 1998), David"
[22] " Firth [ctb]"
[23] "Maintainer: Brian Ripley <[email protected]>"
[24] "Repository: CRAN"
[25] "Date/Publication: 2012-05-28 08:53:03"
[26] "Built: R 2.15.1; x86_64-pc-mingw32; 2012-06-22 14:16:09 UTC; windows"
[27] "Archs: i386, x64"
R>
There is an entire manual devoted to this...
I ran into this problem and was solved by checking the min sdk version in the manifest. It was set to 15 (ICS), but my phone was running 10(Gingerbread)
However, numbering starts at 1
, so:
x = arange(5)
y = np.exp(5)
plt.figure(1)
plt.plot(x, y)
z = np.sin(x)
plt.figure(2)
plt.plot(x, z)
w = np.cos(x)
plt.figure(1) # Here's the part I need, but numbering starts at 1!
plt.plot(x, w)
Also, if you have multiple axes on a figure, such as subplots, use the axes(h)
command where h
is the handle of the desired axes object to focus on that axes.
(don't have comment privileges yet, sorry for new answer!)
When I had this problem, the issue was I did not have the private key necessary for the developer certificate to be valid.
The solution was:
Have the developer who created the certificate export their private key matching the iOS developer public key. see http://developer.apple.com/ios/manage/certificates/team/howto.action
Open this file (Certificates.p12) on your machine (with KeyChain), and enter the password the other developer used when exporting. It is now imported into your KeyChain.
Now connect iOS device and rebuild targeting the iOS device.
When Command Extensions are enabled (Windows XP and newer, roughly), you can use the syntax %~nF (where F is the variable and ~n is the request for its name) to only get the filename.
FOR /R C:\Directory %F in (*.*) do echo %~nF
should echo only the filenames.
Another example for vertically and horizontally centered div or any object(s):
var obj = $("#divID");
var halfsc = $(window).height()/2;
var halfh = $(obj).height() / 2;
var halfscrn = screen.width/2;
var halfobj =$(obj).width() / 2;
var goRight = halfscrn - halfobj ;
var goBottom = halfsc - halfh;
$(obj).css({marginLeft: goRight }).css({marginTop: goBottom });
JavaScript has no built-in general map type (sometimes called associative array or dictionary) which allows to access arbitrary values by arbitrary keys. JavaScript's fundamental data structure is the object, a special type of map which only accepts strings as keys and has special semantics like prototypical inheritance, getters and setters and some further voodoo.
When using objects as maps, you have to remember that the key will be converted to a string value via toString()
, which results in mapping 5
and '5'
to the same value and all objects which don't overwrite the toString()
method to the value indexed by '[object Object]'
. You might also involuntarily access its inherited properties if you don't check hasOwnProperty()
.
JavaScript's built-in array type does not help one bit: JavaScript arrays are not associative arrays, but just objects with a few more special properties. If you want to know why they can't be used as maps, look here.
Eugene Lazutkin already described the basic idea of using a custom hash function to generate unique strings which can be used to look up the associated values as properties of a dictionary object. This will most likely be the fastest solution, because objects are internally implemented as hash tables.
In order to get a unique hash value for arbitrary objects, one possibility is to use a global counter and cache the hash value in the object itself (for example, in a property named __hash
).
A hash function which does this is and works for both primitive values and objects is:
function hash(value) {
return (typeof value) + ' ' + (value instanceof Object ?
(value.__hash || (value.__hash = ++arguments.callee.current)) :
value.toString());
}
hash.current = 0;
This function can be used as described by Eugene. For convenience, we will further wrap it in a Map
class.
Map
implementationThe following implementation will additionally store the key-value-pairs in a doubly linked list in order to allow fast iteration over both keys and values. To supply your own hash function, you can overwrite the instance's hash()
method after creation.
// Linking the key-value-pairs is optional.
// If no argument is provided, linkItems === undefined, i.e. !== false
// --> linking will be enabled
function Map(linkItems) {
this.current = undefined;
this.size = 0;
if(linkItems === false)
this.disableLinking();
}
Map.noop = function() {
return this;
};
Map.illegal = function() {
throw new Error("illegal operation for maps without linking");
};
// Map initialisation from an existing object
// doesn't add inherited properties if not explicitly instructed to:
// omitting foreignKeys means foreignKeys === undefined, i.e. == false
// --> inherited properties won't be added
Map.from = function(obj, foreignKeys) {
var map = new Map;
for(var prop in obj) {
if(foreignKeys || obj.hasOwnProperty(prop))
map.put(prop, obj[prop]);
}
return map;
};
Map.prototype.disableLinking = function() {
this.link = Map.noop;
this.unlink = Map.noop;
this.disableLinking = Map.noop;
this.next = Map.illegal;
this.key = Map.illegal;
this.value = Map.illegal;
this.removeAll = Map.illegal;
return this;
};
// Overwrite in Map instance if necessary
Map.prototype.hash = function(value) {
return (typeof value) + ' ' + (value instanceof Object ?
(value.__hash || (value.__hash = ++arguments.callee.current)) :
value.toString());
};
Map.prototype.hash.current = 0;
// --- Mapping functions
Map.prototype.get = function(key) {
var item = this[this.hash(key)];
return item === undefined ? undefined : item.value;
};
Map.prototype.put = function(key, value) {
var hash = this.hash(key);
if(this[hash] === undefined) {
var item = { key : key, value : value };
this[hash] = item;
this.link(item);
++this.size;
}
else this[hash].value = value;
return this;
};
Map.prototype.remove = function(key) {
var hash = this.hash(key);
var item = this[hash];
if(item !== undefined) {
--this.size;
this.unlink(item);
delete this[hash];
}
return this;
};
// Only works if linked
Map.prototype.removeAll = function() {
while(this.size)
this.remove(this.key());
return this;
};
// --- Linked list helper functions
Map.prototype.link = function(item) {
if(this.size == 0) {
item.prev = item;
item.next = item;
this.current = item;
}
else {
item.prev = this.current.prev;
item.prev.next = item;
item.next = this.current;
this.current.prev = item;
}
};
Map.prototype.unlink = function(item) {
if(this.size == 0)
this.current = undefined;
else {
item.prev.next = item.next;
item.next.prev = item.prev;
if(item === this.current)
this.current = item.next;
}
};
// --- Iterator functions - only work if map is linked
Map.prototype.next = function() {
this.current = this.current.next;
};
Map.prototype.key = function() {
return this.current.key;
};
Map.prototype.value = function() {
return this.current.value;
};
The following script,
var map = new Map;
map.put('spam', 'eggs').
put('foo', 'bar').
put('foo', 'baz').
put({}, 'an object').
put({}, 'another object').
put(5, 'five').
put(5, 'five again').
put('5', 'another five');
for(var i = 0; i++ < map.size; map.next())
document.writeln(map.hash(map.key()) + ' : ' + map.value());
generates this output:
string spam : eggs
string foo : baz
object 1 : an object
object 2 : another object
number 5 : five again
string 5 : another five
PEZ suggested to overwrite the toString()
method, presumably with our hash function. This is not feasible, because it doesn't work for primitive values (changing toString()
for primitives is a very bad idea). If we want toString()
to return meaningful values for arbitrary objects, we would have to modify Object.prototype
, which some people (myself not included) consider verboten.
The current version of my Map
implementation as well as other JavaScript goodies can be obtained from here.
I don't know what you want to do, but this is how I actually translated your example code....
package test;
/**
* @author The Elite Gentleman
*
*/
public enum Strings {
STRING_ONE("ONE"),
STRING_TWO("TWO")
;
private final String text;
/**
* @param text
*/
Strings(final String text) {
this.text = text;
}
/* (non-Javadoc)
* @see java.lang.Enum#toString()
*/
@Override
public String toString() {
return text;
}
}
Alternatively, you can create a getter method for text
.
You can now do Strings.STRING_ONE.toString();
my best solution :
WHERE
COALESCE(char_length(fieldValue), 0) = 0
COALESCE returns the first non-null expr in the expression list().
if the fieldValue is null or empty string then: we will return the second element then 0.
so 0 is equal to 0 then this fieldValue is a null or empty string.
in python for exemple:
def coalesce(fieldValue):
if fieldValue in (null,''):
return 0
good luck
I only use MicrosoftAdvertising.Mobile and Microsoft.Advertising.Mobile.UI and I am served ads. The SDK should only add the DLLs not reference itself.
Note: You need to explicitly set width and height Make sure the phone dialer, and web browser capabilities are enabled
Followup note: Make sure that after you've removed the SDK DLL, that the xmlns references are not still pointing to it. The best route to take here is
Here is the xmlns reference:
xmlns:AdNamepace="clr-namespace:Microsoft.Advertising.Mobile.UI;assembly=Microsoft.Advertising.Mobile.UI"
Then the ad itself:
<AdNamespace:AdControl x:Name="myAd" Height="80" Width="480" AdUnitId="yourAdUnitIdHere" ApplicationId="yourIdHere"/>
The escape code for a percent sign is "%%", so your code would look like this
[NSString stringWithFormat:@"%d%%", someDigit];
Also, all the other format specifiers can be found at Conceptual Strings Articles
here is what works with the version of the program that I'm using: may work for you too.
I will just place the instruction and command that does it. class is the name of the table. you change it in the table its self with this method. not just the return on the search process.
view the table class
select * from class
change the length of the columns FacID (seen as "faci") and classnumber (seen as "classnu") to fit the whole labels.
alter table class modify facid varchar (5);
alter table class modify classnumber varchar(11);
view table again to see the difference
select * from class;
(run the command again to see the difference)
This changes the the actual table for good, but for better.
P.S. I made these instructions up as a note for the commands. This is not a test, but can help on one :)
Here are the differences that I know about:
I also face the same issue "OpenCV NoneType object has no attribute shape" and i solve this by changing the image location. I also use the PyCharm IDE. Currently my image location and class file in the same folder.
yes! you should be using pip as your python package manager ( http://pypi.python.org/pypi/pip )
with pip installed packages, you can do a
pip freeze
and it will list all installed packages. You should probably also be using virtualenv and virtualenvwrapper. When you start a new project, you can do
mkvirtualenv my_new_project
and then (inside that virtualenv), do
pip install all_your_stuff
This way, you can workon my_new_project
and then pip freeze
to see which packages are installed for that virtualenv/project.
for example:
? ~ mkvirtualenv yo_dude
New python executable in yo_dude/bin/python
Installing setuptools............done.
Installing pip...............done.
virtualenvwrapper.user_scripts creating /Users/aaylward/dev/virtualenvs/yo_dude/bin/predeactivate
virtualenvwrapper.user_scripts creating /Users/aaylward/dev/virtualenvs/yo_dude/bin/postdeactivate
virtualenvwrapper.user_scripts creating /Users/aaylward/dev/virtualenvs/yo_dude/bin/preactivate
virtualenvwrapper.user_scripts creating /Users/aaylward/dev/virtualenvs/yo_dude/bin/postactivate
virtualenvwrapper.user_scripts creating /Users/aaylward/dev/virtualenvs/yo_dude/bin/get_env_details
(yo_dude)? ~ pip install django
Downloading/unpacking django
Downloading Django-1.4.1.tar.gz (7.7Mb): 7.7Mb downloaded
Running setup.py egg_info for package django
Installing collected packages: django
Running setup.py install for django
changing mode of build/scripts-2.7/django-admin.py from 644 to 755
changing mode of /Users/aaylward/dev/virtualenvs/yo_dude/bin/django-admin.py to 755
Successfully installed django
Cleaning up...
(yo_dude)? ~ pip freeze
Django==1.4.1
wsgiref==0.1.2
(yo_dude)? ~
or if you have a python package with a requirements.pip file,
mkvirtualenv my_awesome_project
pip install -r requirements.pip
pip freeze
will do the trick
Not a full answer Ok so this is just to supplement the information about parseInt, which is still very valid. Express doesn't allow the req or res objects to be modified at all (immutable). So if you want to modify/use this data effectively, you must copy it to another variable (var year = req.params.year).
I think you need something a bit more generic. Try this:
public static System.Boolean IsNumeric (System.Object Expression)
{
if(Expression == null || Expression is DateTime)
return false;
if(Expression is Int16 || Expression is Int32 || Expression is Int64 || Expression is Decimal || Expression is Single || Expression is Double || Expression is Boolean)
return true;
try
{
if(Expression is string)
Double.Parse(Expression as string);
else
Double.Parse(Expression.ToString());
return true;
} catch {} // just dismiss errors but return false
return false;
}
}
Hope it helps!
You could use prop
as well. Check the following code below.
$(document).ready(function(){
$('.staff_on_site').click(function(){
var rBtnVal = $(this).val();
if(rBtnVal == "yes"){
$("#no_of_staff").prop("readonly", false);
}
else{
$("#no_of_staff").prop("readonly", true);
}
});
});
I had written this method to turn on the screen after screen lock. It works perfectly for me. Try it-
private void unlockScreen() {
Window window = this.getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
window.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
window.addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
}
And call this method from onResume()
.
There are two possible solutions for these kind of situations:
Add a unique suffix to the image src
to force browser downloading it again, like this:
var img = new Image();
img.src = "img.jpg?_="+(new Date().getTime());
img.onload = function () {
alert("image is loaded");
}
In this code every time adding current timestamp to the end of the image URL you make it unique and browser will download the image again
Simple Definition
SRC : (Source). To specify the origin of (a communication); document:
HREF : (Hypertext Reference). A reference or link to another page, document...
I had same error, I think the problem is that the error text is confusing, because its giving a false key name.
In your case It should say "There is no ViewData item of type 'IEnumerable' that has the key "Submarkets"".
My error was a misspelling in the view code (your "Submarkets"), but the error text made me go crazy.
I post this answer because I want to say people looking for this error, like I was, that the problem is that its not finding the IENumerable, but in the var that its supposed to look for it ("Submarkets" in this case), not in the one showed in error ("submarket_0").
Accepted answer is very interesting, but as you said the convention is applied if you dont specify the 2nd parameter, in this case it was specified, but the var was not found (in your case because the viewdata had not it, in my case because I misspelled the var name)
Hope this helps!
1.
first of all Port 80(or what ever you are using) and 443 must be allow for both TCP and UDP packets. To do this, create 2 inbound rules for TPC and UDP on Windows Firewall for port 80 and 443. (or you can disable your whole firewall for testing but permanent solution if allow inbound rule)
2.
You need to change the security setting on Apache to allow access from anywhere else, so edit your httpd.conf
file.
Change this section from :
# onlineoffline tag - don't remove
Order Deny,Allow
Deny from all
Allow from 127.0.0.1
Allow from ::1
Allow from localhost
To :
# onlineoffline tag - don't remove
Order Allow,Deny
Allow from all
if "Allow from all" line not work for your then use "Require all granted" then it will work for you.
In version 3 and > of WAMPServer there is a Virtual Hosts pre defined for localhost
so dont amend the httpd.conf
file at all, leave it as you found it.
Using the menus, edit the httpd-vhosts.conf
file.
It should look like this :
<VirtualHost *:80>
ServerName localhost
DocumentRoot D:/wamp/www
<Directory "D:/wamp/www/">
Options +Indexes +FollowSymLinks +MultiViews
AllowOverride All
Require local
</Directory>
</VirtualHost>
Amend it to
<VirtualHost *:80>
ServerName localhost
DocumentRoot D:/wamp/www
<Directory "D:/wamp/www/">
Options +Indexes +FollowSymLinks +MultiViews
AllowOverride All
Require all granted
</Directory>
</VirtualHost>
Note:if you are running wamp for other than port 80 then VirtualHost will be like VirtualHost *:86.(86 or port whatever you are using) instead of VirtualHost *:80
3. Dont forget to restart All Services of Wamp or Apache after making this change
I have been exactly in your case in the past. And I went for magic methods.
This was a mistake, the last part of your question says it all :
@property
phpdoc annotation but that requires to maintain them: quite a pain)getXXX()
is not only returning a private property but doing real logic. You have the same naming. For example you have $user->getName()
(returns private property) and $user->getToken($key)
(computed). The day your getter gets more than a getter and needs to do some logic, everything is still consistent.Finally, and this is the biggest problem IMO : this is magic. And magic is very very bad, because you have to know how the magic works to use it properly. That's a problem I've met in a team: everybody has to understand the magic, not just you.
Getters and setters are a pain to write (I hate them) but they are worth it.
in hibernate 5.x, you should add set hibernate.id.new_generator_mappings to false in hibernate.cfg.xml
<session-factory>
......
<property name="show_sql">1</property>
<property name="hibernate.id.new_generator_mappings">false</property>
......
</session-factory>
If value
is unindexed, both result in a table-scan. The performance difference in this scenario will be negligible.
If value
is indexed, as Daniel points out in his comment, the =
will result in an index lookup which is O(log N) performance. The LIKE will (most likely - depending on how selective it is) result in a partial scan of the index >= 'abc'
and < 'abd'
which will require more effort than the =
.
Note that I'm talking SQL Server here - not all DBMSs will be nice with LIKE.
In XAML:
<StackPanel FocusManager.FocusedElement="{Binding ElementName=Box}">
<TextBox Name="Box" />
</StackPanel>
The easiest might be:
Array(1, 2, 3) :+ 4
Actually, Array can be implcitly transformed in a WrappedArray
Check the location of your library, for example lxxx.so:
locate lxxx.so
If it is not in the /usr/lib
folder, type this:
sudo cp yourpath/lxxx.so /usr/lib
Done.
Just change
C:\Users\Giacomo B\AppData\Local\Android\sdk
to
C:\Users\Giacomo_B\AppData\Local\Android\sdk
Use a FULL OUTER JOIN:
select
a.col_a,
a.col_b,
b.col_c
from
(select col_a,col_bfrom tab1) a
join
(select col_a,col_cfrom tab2) b
on a.col_a= b.col_a
There is a straight forward clean solution available. Use the wholeTextFiles() method. This will take a directory and forms a key value pair. The returned RDD will be a pair RDD. Find below the description from Spark docs:
SparkContext.wholeTextFiles lets you read a directory containing multiple small text files, and returns each of them as (filename, content) pairs. This is in contrast with textFile, which would return one record per line in each file
Just pass the object reference to the following function and you will get the index
function thisindex(elm)
{
var the_li = elm;
var the_ul = elm.parentNode;
var li_list = the_ul.childNodes;
var count = 0; // Tracks the index of LI nodes
// Step through all the child nodes of the UL
for( var i = 0; i < li_list.length; i++ )
{
var node = li_list.item(i);
if( node )
{
// Check to see if the node is a LI
if( node.nodeName == "LI" )
{
// Increment the count of LI nodes
count++;
// Check to see if this node is the one passed in
if( the_li == node )
{
// If so, alert the current count
alert(count-1);
}
}
}
}
}
using PhpMyAdmin version 4.5.4.1deb2ubuntu2, you can set the variables in /etc/phpmyadmin/config-db.php
so set $dbserver
to your server name, e.g. $dbserver='mysql.example.com';
<?php
##
## database access settings in php format
## automatically generated from /etc/dbconfig-common/phpmyadmin.conf
## by /usr/sbin/dbconfig-generate-include
##
## by default this file is managed via ucf, so you shouldn't have to
## worry about manual changes being silently discarded. *however*,
## you'll probably also want to edit the configuration file mentioned
## above too.
##
$dbuser='phpmyadmin';
$dbpass='P@55w0rd';
$basepath='';
$dbname='phpmyadmin';
$dbserver='localhost';
$dbport='';
$dbtype='mysql';
Most likely your query failed, and the query call returned a boolean FALSE (or an error object of some sort), which you then try to use as if was a resultset object, causing the error. Try something like var_dump($result)
to see what you really got.
Check for errors after EVERY database query call. Even if the query itself is syntactically valid, there's far too many reasons for it to fail anyways - checking for errors every time will save you a lot of grief at some point.
How about creating your own Custom Panel class? That way you won't have to worry about overriding Bootstrap.
HTML
<div class="panel panel-custom-horrible-red">
<div class="panel-heading">
<h3 class="panel-title">Panel title</h3>
</div>
<div class="panel-body">
Panel content
</div>
</div>
CSS
.panel-custom-horrible-red {
border-color: #ff0000;
}
.panel-custom-horrible-red > .panel-heading {
background: #ff0000;
color: #ffffff;
border-color: #ff0000;
}
Fiddle: https://jsfiddle.net/x05f4crg/1/
I had the same error and ended up solving it by upgrading my Oracle ojdbc driver to a version compatible with the Oracle database version
Open Anaconda cmd in base mode:
Then use conda update conda to update Anaconda.
You can then use conda update --all to update all the requirements for Anaconda:
conda update conda
conda update --all
I think to be consistant it's nicer to use @throw with your own class that extends NSException. Then you use the same notations for try catch finally:
@try {
.....
}
@catch{
...
}
@finally{
...
}
Apple explains here how to throw and handle exceptions: Catching Exceptions Throwing Exceptions
Try this tutorial it has the explanation and it will be helpful http://www.ccs.neu.edu/home/kathleen/classes/cs3200/JDBCtutorial.pdf
run sudo npm install ngrok --g a very simple way to install
sudo because you are installing it globally
To create a new screen with the name foo
, use
screen -S foo
Then to reattach it, run
screen -r foo # or use -x, as in
screen -x foo # for "Multi display mode" (see the man page)
The accepted answer implies this, but I'd like to make explicit the connection to shell builtins:
As mentioned already, export
will make a variable available to both the shell and children. If export
is not used, the variable will only be available in the shell, and only shell builtins can access it.
That is,
tango=3
env | grep tango # prints nothing, since env is a child process
set | grep tango # prints tango=3 - "type set" shows `set` is a shell builtin
I prefer TIMESTAMPDIFF because you can easily change the unit if need be.
add -e
key for passing environment variables to container.
example:
$ MYSQLHOSTIP=$(sudo docker inspect -format="{{ .NetworkSettings.IPAddress }}" $MYSQL_CONRAINER_ID)
$ sudo docker run -e DBIP=$MYSQLHOSTIP -i -t myimage /bin/bash
root@87f235949a13:/# echo $DBIP
172.17.0.2
When you need built-in indexed access, sorting (and after this binary searching), and "ToArray()" method, you should use List.
I actually had solved this not long after posting but failed to post my solution. I honestly don't remember it. But, I had to re-visit the task when I was given a new project that faced the same challenge.
I used the ReceivedTime property of Outlook.MailItem to get the time-stamp, I was able to use this as a unique identifier for each file so they do not override one another.
Public Sub saveAttachtoDisk(itm As Outlook.MailItem)
Dim objAtt As Outlook.Attachment
Dim saveFolder As String
saveFolder = "C:\PathToDirectory\"
Dim dateFormat As String
dateFormat = Format(itm.ReceivedTime, "yyyy-mm-dd Hmm ")
For Each objAtt In itm.Attachments
objAtt.SaveAsFile saveFolder & "\" & dateFormat & objAtt.DisplayName
Next
End Sub
Thanks a ton for the other solutions, many of them go above an beyond :)
Add the following to the top of your file # coding=utf-8
If you go to the link in the error you can seen the reason why:
Defining the Encoding
Python will default to ASCII as standard encoding if no other encoding hints are given. To define a source code encoding, a magic comment must be placed into the source files either as first or second line in the file, such as: # coding=
Useful sns.heatmap
api is here. Check out the parameters, there are a good number of them. Example:
import seaborn as sns
%matplotlib inline
idx= ['aaa','bbb','ccc','ddd','eee']
cols = list('ABCD')
df = DataFrame(abs(np.random.randn(5,4)), index=idx, columns=cols)
# _r reverses the normal order of the color map 'RdYlGn'
sns.heatmap(df, cmap='RdYlGn_r', linewidths=0.5, annot=True)
Okay so you are trying to get a bitmap from a file? Title says URL. Anyways, when you are getting files from external storage in Android you should never use a direct path. Instead call getExternalStorageDirectory() like so:
File bitmapFile = new File(Environment.getExternalStorageDirectory() + "/" + PATH_TO_IMAGE);
Bitmap bitmap = BitmapFactory.decodeFile(bitmapFile);
getExternalStorageDirectory() gives you the path to the SD card. Also you need to declare the WRITE_EXTERNAL_STORAGE permission in the Manifest.
Try this.
Does not require any options to change.
Does not require any command line activity.
Just run software and you will done the job.
www.vhghorecha.in/unhide-all-files-folders-virus/
Happy Knowledge Sharing
In iOS 7 the status bar doesn't have a background, therefore if you put a black 20px-high view behind it you will achieve the same result as iOS 6.
Also you may want to read the iOS 7 UI Transition Guide for further information on the subject.
No -P needed; -E is sufficient:
grep -E '(^|\s)abc(\s|$)'
or even without -E:
grep '\(^\|\s\)abc\(\s\|$\)'
Does m
really need to be a data.frame()
or will a matrix()
suffice?
m <- matrix(0, ncol = 30, nrow = 2)
You can wrap a data.frame()
around that if you need to:
m <- data.frame(m)
or all in one line: m <- data.frame(matrix(0, ncol = 30, nrow = 2))
Try the following code:
ActivityManager activityManager = (ActivityManager) newContext.getSystemService( Context.ACTIVITY_SERVICE );
List<RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
for(RunningAppProcessInfo appProcess : appProcesses){
if(appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND){
Log.i("Foreground App", appProcess.processName);
}
}
Process name is the package name of the app running in foreground. Compare it to the package name of your application. If it is the same then your application is running on foreground.
I hope this answers your question.
There is no out of the box DateTime picker for WPF..
There are however a lot of third party DateTime pickers of course :)
http://www.devcomponents.com/dotnetbar-wpf/WPFDateTimePicker.aspx
http://marlongrech.wordpress.com/2007/09/11/wpf-datepicker/
http://www.codeplex.com/AvalonControlsLib
Just do a quick google to find more!
If you just need a good date-parsing function, I would look at date.js. It will take just about any date string you can throw at it, and return you a JavaScript Date object.
Once you have a Date object, you can call its getTime() method, which will give you milliseconds since January 1, 1970. Just divide that result by 1000 to get the unix timestamp value.
In code, just include date.js, then:
var unixtime = Date.parse("24-Nov-2009 17:57:35").getTime()/1000
I prefer this. timeit
doc is far too confusing.
from datetime import datetime
start_time = datetime.now()
# INSERT YOUR CODE
time_elapsed = datetime.now() - start_time
print('Time elapsed (hh:mm:ss.ms) {}'.format(time_elapsed))
Note, that there isn't any formatting going on here, I just wrote hh:mm:ss
into the printout so one can interpret time_elapsed
There's a whole bunch of things that can cause this. I'd read through these and try each of them
http://dev.mysql.com/doc/refman/5.1/en/gone-away.html
I've worked for several web hosting companies over the years and generally when I see this, it is the wait_timeout on the server end though this doesn't appear to be the case here.
If you find the solution, I hope you post it. I'd like to know.
You can use numpy to convert a list directly to a floating array or matrix.
import numpy as np
list_ex = [1, 0] # This a list
list_int = np.array(list_ex) # This is a numpy integer array
If you want to convert the integer array to a floating array then add 0. to it
list_float = np.array(list_ex) + 0. # This is a numpy floating array
Here's a code excerpt we're using in our app to set request headers. You'll note we set the CONTENT_TYPE header only on a POST or PUT, but the general method of adding headers (via a request interceptor) is used for GET as well.
/**
* HTTP request types
*/
public static final int POST_TYPE = 1;
public static final int GET_TYPE = 2;
public static final int PUT_TYPE = 3;
public static final int DELETE_TYPE = 4;
/**
* HTTP request header constants
*/
public static final String CONTENT_TYPE = "Content-Type";
public static final String ACCEPT_ENCODING = "Accept-Encoding";
public static final String CONTENT_ENCODING = "Content-Encoding";
public static final String ENCODING_GZIP = "gzip";
public static final String MIME_FORM_ENCODED = "application/x-www-form-urlencoded";
public static final String MIME_TEXT_PLAIN = "text/plain";
private InputStream performRequest(final String contentType, final String url, final String user, final String pass,
final Map<String, String> headers, final Map<String, String> params, final int requestType)
throws IOException {
DefaultHttpClient client = HTTPClientFactory.newClient();
client.getParams().setParameter(HttpProtocolParams.USER_AGENT, mUserAgent);
// add user and pass to client credentials if present
if ((user != null) && (pass != null)) {
client.getCredentialsProvider().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, pass));
}
// process headers using request interceptor
final Map<String, String> sendHeaders = new HashMap<String, String>();
if ((headers != null) && (headers.size() > 0)) {
sendHeaders.putAll(headers);
}
if (requestType == HTTPRequestHelper.POST_TYPE || requestType == HTTPRequestHelper.PUT_TYPE ) {
sendHeaders.put(HTTPRequestHelper.CONTENT_TYPE, contentType);
}
// request gzip encoding for response
sendHeaders.put(HTTPRequestHelper.ACCEPT_ENCODING, HTTPRequestHelper.ENCODING_GZIP);
if (sendHeaders.size() > 0) {
client.addRequestInterceptor(new HttpRequestInterceptor() {
public void process(final HttpRequest request, final HttpContext context) throws HttpException,
IOException {
for (String key : sendHeaders.keySet()) {
if (!request.containsHeader(key)) {
request.addHeader(key, sendHeaders.get(key));
}
}
}
});
}
//.... code omitted ....//
}
Changes to be committed: (use "git reset HEAD ..." to unstage)
Features of C# Absent in Java • C# includes more primitive types and the functionality to catch arithmetic exceptions.
• Includes a large number of notational conveniences over Java, many of which, such as operator overloading and user-defined casts, are already familiar to the large community of C++ programmers.
• Event handling is a "first class citizen"—it is part of the language itself.
• Allows the definition of "structs", which are similar to classes but may be allocated on the stack (unlike instances of classes in C# and Java).
• C# implements properties as part of the language syntax.
• C# allows switch statements to operate on strings.
• C# allows anonymous methods providing closure functionality.
• C# allows iterator that employs co-routines via a functional-style yield keyword.
• C# has support for output parameters, aiding in the return of multiple values, a feature shared by C++ and SQL.
• C# has the ability to alias namespaces.
• C# has "Explicit Member Implementation" which allows a class to specifically implement methods of an interface, separate from its own class methods. This allows it also to implement two different interfaces which happen to have a method of the same name. The methods of an interface do not need to be public; they can be made to be accessible only via that interface.
• C# provides integration with COM.
• Following the example of C and C++, C# allows call by reference for primitive and reference types.
Features of Java Absent in C#
• Java's strictfp keyword guarantees that the result of floating point operations remain the same across platforms.
• Java supports checked exceptions for better enforcement of error trapping and handling.
To save your work and exit press Esc and then :wq (w for write and q for quit).
Alternatively, you could both save and exit by pressing Esc and then :x
To set another editor run export EDITOR=myFavoriteEdior
on your terminal, where myFavoriteEdior
can be vi
, gedit
, subl
(for sublime) etc.
We can use the modulo (%) operator. This tells us how many remainders we have when we divide x by y - expresses as x % y
. Every whole number must divide by 1, so if there is a remainder, it must not be a whole number.
This function will return a boolean, True
or False
, depending on whether n
is a whole number.
def is_whole(n):
return n % 1 == 0
You can use the min and max attributes.
The following code do the same:
<input type="number" min="-999" max="9999"/>
This goes back and forth to and from the \uXXXX format.
class Program {
static void Main( string[] args ) {
string unicodeString = "This function contains a unicode character pi (\u03a0)";
Console.WriteLine( unicodeString );
string encoded = EncodeNonAsciiCharacters(unicodeString);
Console.WriteLine( encoded );
string decoded = DecodeEncodedNonAsciiCharacters( encoded );
Console.WriteLine( decoded );
}
static string EncodeNonAsciiCharacters( string value ) {
StringBuilder sb = new StringBuilder();
foreach( char c in value ) {
if( c > 127 ) {
// This character is too big for ASCII
string encodedValue = "\\u" + ((int) c).ToString( "x4" );
sb.Append( encodedValue );
}
else {
sb.Append( c );
}
}
return sb.ToString();
}
static string DecodeEncodedNonAsciiCharacters( string value ) {
return Regex.Replace(
value,
@"\\u(?<Value>[a-zA-Z0-9]{4})",
m => {
return ((char) int.Parse( m.Groups["Value"].Value, NumberStyles.HexNumber )).ToString();
} );
}
}
Outputs:
This function contains a unicode character pi (p)
This function contains a unicode character pi (\u03a0)
This function contains a unicode character pi (p)
LINUX
struct timeval tv;
tv.tv_sec = 30; // 30 Secs Timeout
tv.tv_usec = 0; // Not init'ing this can cause strange errors
setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv,sizeof(struct timeval));
WINDOWS
DWORD timeout = SOCKET_READ_TIMEOUT_SEC * 1000;
setsockopt(socket, SOL_SOCKET, SO_RCVTIMEO, (const char*)&timeout, sizeof(timeout));
NOTE: You have put this setting before bind()
function call for proper run
May 2018 react-native version 0.55.2
secureTextEntry={true} works
password={true} does not work
Use compareTo()
Return Values
0 if the argument Date is equal to this Date; a value less than 0 if this Date is before the Date argument; and a value greater than 0 if this Date is after the Date argument.
Like
if(date1.compareTo(date2)>0)
The question asks which characters are allowed in GET parameters without encoding or escaping them.
According to RFC3986 (general URL syntax) and RFC7230, section 2.7.1 (HTTP/S URL syntax) the only characters you need to percent-encode are those outside of the query set, see the definition below.
However, there are additional specifications like HTML5, Web forms, and the obsolete Indexed search, W3C recommendation. Those documents add a special meaning to some characters notably, to symbols like = & + ;.
Other answers here suggest that most of the reserved characters should be encoded, including "/" "?". That's not correct. In fact, RFC3986, section 3.4 advises against percent-encoding "/" "?" characters.
it is sometimes better for usability to avoid percent- encoding those characters.
RFC3986 defines query component as:
query = *( pchar / "/" / "?" )
pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
pct-encoded = "%" HEXDIG HEXDIG
sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "="
unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
A percent-encoding mechanism is used to represent a data octet in a component when that octet's corresponding character is outside the allowed set or is being used as a delimiter of, or within, the component.
The conclusion is that XYZ part should encode:
special: # % = & ;
Space
sub-delims
out of query set: [ ]
non ASCII encodable characters
Unless special symbols = & ; are key=value separators.
Encoding other characters is allowed but not necessary.
What about something like this?
<?php
$URL = "http://example.com";
$base = '<base href="'.$URL.'">';
$host = preg_replace('/^[^\/]+\/\//', '', $URL);
$tarray = explode('/', $host);
$host = array_shift($tarray);
$URI = '/' . implode('/', $tarray);
$content = '';
$fp = @fsockopen($host, 80, $errno, $errstr, 30);
if(!$fp) { echo "Unable to open socked: $errstr ($errno)\n"; exit; }
fwrite($fp,"GET $URI HTTP/1.0\r\n");
fwrite($fp,"Host: $host\r\n");
if( isset($_SERVER["HTTP_USER_AGENT"]) ) { fwrite($fp,'User-Agent: '.$_SERVER
["HTTP_USER_AGENT"]."\r\n"); }
fwrite($fp,"Connection: Close\r\n");
fwrite($fp,"\r\n");
while (!feof($fp)) { $content .= fgets($fp, 128); }
fclose($fp);
if( strpos($content,"\r\n") > 0 ) { $eolchar = "\r\n"; }
else { $eolchar = "\n"; }
$eolpos = strpos($content,"$eolchar$eolchar");
$content = substr($content,($eolpos + strlen("$eolchar$eolchar")));
if( preg_match('/<head\s*>/i',$content) ) { echo( preg_replace('/<head\s*>/i','<head>'.
$base,$content,1) ); }
else { echo( preg_replace('/<([a-z])([^>]+)>/i',"<\\1\\2>".$base,$content,1) ); }
?>
According to this link, it is possible to use ddms in the tools directory of the android sdk to take screen captures.
To do this within an application (and not during development), there are also applications to do so. But as @zed_0xff points out it certainly requires root.
Take command prompt with administrator privilege
Change directory to where the .sql file stored
Execute the following command
sqlcmd -S 'your server name' -U 'user name of server' -P 'password of server' -d 'db name'-i script.sql
<input type='text'
name='t1'
id='t1'
maxlength=10
placeholder='typing some text' >
<p></p>
This is the text box, it has a fixed length of 10 characters, and if you can try but this text box does not contain maximum length 10 character
In English:
It's a
List
of some type that extends the classHasWord
, includingHasWord
In general the ?
in generics means any class. And the extends SomeClass
specifies that that object must extend SomeClass
(or be that class).
If you want something like : InputString => StringPart1...StringPart2
HTML:
<html ng-app="myApp">
<body>
{{ "AngularJS string limit example" | strLimit: 10 : 20 }}
</body>
</html>
Angular Code:
var myApp = angular.module('myApp', []);
myApp.filter('strLimit', ['$filter', function($filter) {
return function(input, beginlimit, endlimit) {
if (! input) return;
if (input.length <= beginlimit + endlimit) {
return input;
}
return $filter('limitTo')(input, beginlimit) + '...' + $filter('limitTo')(input, -endlimit) ;
};
}]);
Example with following parameters :
beginLimit = 10
endLimit = 20
Before:
- /home/house/room/etc/ava_B0363852D549079E3720DF6680E17036.jar
After:
- /home/hous...3720DF6680E17036.jar
I had to put it in double quotes.
date_default_timezone_set("America/Los_Angeles"); // default time zone
This does not answer the question directly. But someone may end up here because they want to run a oneliner of R from the terminal. For example, if you just want to install some missing packages and quit, this oneliner can be very convenient. I use it a lot when I suddenly find out that I miss some packages, and I want to install them to where I want.
To install to the default location:
R -e 'install.packages(c("package1", "package2"))'
To install to a location that requires root
privileges:
R -e 'install.packages(c("package1", "package2"), lib="/usr/local/lib/R/site-library")'
Encountered similar error. resetting chrome://net-internals/#hsts did not work for me. The issue was that my vm's clock was skewed by days. resetting the time did work out to resolve this issue. https://support.google.com/chrome/answer/4454607?hl=en
parseInt()
with radix is a best solution (as was told by many):
But if you want to implement it without parseInt, here is an implementation:
function bin2dec(num){
return num.split('').reverse().reduce(function(x, y, i){
return (y === '1') ? x + Math.pow(2, i) : x;
}, 0);
}
In this case, insert a single else
:
public void Method()
{
if(something)
{
// some code
if(something2)
{
// now I should break from ifs and go to te code outside ifs
}
else return;
}
// The code i want to go if the second if is true
}
Generally: There is no break
in an if/else
sequence, simply arrange your code correctly in if / if else / else
clauses.
In python, you wouldn't normally do what you are trying to do. But, the below code will do it:
strs = ["" for x in range(size)]
wxWidgets has a very rich string API wxString
it can be done with (using the case conversion way)
int Contains(const wxString& SpecProgramName, const wxString& str)
{
wxString SpecProgramName_ = SpecProgramName.Upper();
wxString str_ = str.Upper();
int found = SpecProgramName.Find(str_);
if (wxNOT_FOUND == found)
{
return 0;
}
return 1;
}
I've just had the same problem (with Python 2.7 and PIL for this versions, but the solution should work also for 2.6) and the way to solve it is to copy all the registry keys from:
HKEY_LOCAL_MACHINE\SOFTWARE\Python
to
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Python
Worked for me
solution found at the address below so credits should go there: http://effbot.slinkset.com/items/Adding_Python_Information_to_the_Windows_Registry
this
refers to a reference of the current class.
super
refers to the parent of the current class (which called the super
keyword).
By doing this
, it allows you to access methods/attributes of the current class (including its own private methods/attributes).
super
allows you to access public/protected method/attributes of parent(base) class. You cannot see the parent's private method/attributes.
A bit involved. Easiest would be to refer to this SQL Fiddle I created for you that produces the exact result. There are ways you can improve it for performance or other considerations, but this should hopefully at least be clearer than some alternatives.
The gist is, you get a canonical ranking of your data first, then use that to segment the data into groups, then find an end date for each group, then eliminate any intermediate rows. ROW_NUMBER() and CROSS APPLY help a lot in doing it readably.
EDIT 2019:
The SQL Fiddle does in fact seem to be broken, for some reason, but it appears to be a problem on the SQL Fiddle site. Here's a complete version, tested just now on SQL Server 2016:
CREATE TABLE Source
(
EmployeeID int,
DateStarted date,
DepartmentID int
)
INSERT INTO Source
VALUES
(10001,'2013-01-01',001),
(10001,'2013-09-09',001),
(10001,'2013-12-01',002),
(10001,'2014-05-01',002),
(10001,'2014-10-01',001),
(10001,'2014-12-01',001)
SELECT *,
ROW_NUMBER() OVER (PARTITION BY EmployeeID ORDER BY DateStarted) AS EntryRank,
newid() as GroupKey,
CAST(NULL AS date) AS EndDate
INTO #RankedData
FROM Source
;
UPDATE #RankedData
SET GroupKey = beginDate.GroupKey
FROM #RankedData sup
CROSS APPLY
(
SELECT TOP 1 GroupKey
FROM #RankedData sub
WHERE sub.EmployeeID = sup.EmployeeID AND
sub.DepartmentID = sup.DepartmentID AND
NOT EXISTS
(
SELECT *
FROM #RankedData bot
WHERE bot.EmployeeID = sup.EmployeeID AND
bot.EntryRank BETWEEN sub.EntryRank AND sup.EntryRank AND
bot.DepartmentID <> sup.DepartmentID
)
ORDER BY DateStarted ASC
) beginDate (GroupKey);
UPDATE #RankedData
SET EndDate = nextGroup.DateStarted
FROM #RankedData sup
CROSS APPLY
(
SELECT TOP 1 DateStarted
FROM #RankedData sub
WHERE sub.EmployeeID = sup.EmployeeID AND
sub.DepartmentID <> sup.DepartmentID AND
sub.EntryRank > sup.EntryRank
ORDER BY EntryRank ASC
) nextGroup (DateStarted);
SELECT * FROM
(
SELECT *, ROW_NUMBER() OVER (PARTITION BY GroupKey ORDER BY EntryRank ASC) AS GroupRank FROM #RankedData
) FinalRanking
WHERE GroupRank = 1
ORDER BY EntryRank;
DROP TABLE #RankedData
DROP TABLE Source
The Following:
.show-grid [class*="span"] {
means that all child elements of '.show-grid' with a class that CONTAINS the word 'span' in it will acquire those CSS properties.
<div class="show-grid">
<div class="span">.span</div>
<div class="span6">span6</div>
<div class="attention-span">attention</div>
<div class="spanish">spanish</div>
<div class="mariospan">mariospan</div>
<div class="espanol">espanol</div>
<div>
<div class="span">.span</div>
</div>
<p class="span">span</p>
<span class="span">I do GET HIT</span>
<span>I DO NOT GET HIT since I need a class of 'span'</span>
</div>
<div class="span">I DO NOT GET HIT since I'm outside of .show-grid</span>
All of the elements get hit except for the <span>
by itself.
In Regards to Bootstrap:
span6
: this was Bootstrap 2's scaffolding technique which divided a section into a horizontal grid, based on parts of 12. Thus span6
would have a width of 50%..col-*
classes (e.g. col-sm-6
), which also specifies a media breakpoint to handle responsiveness when the window shrinks below a certain size. Check Bootstrap 4.1 and Bootstrap 3.3.7 for more documentation. I would recommend going with a later Bootstrap nowadaysIssue:
.Net application code aborts before it starts its execution [Console application or Windows application]
Error received: Aborted with Error code "E0434352"
Exception: Unknown exception
Scenario 1:
When an application is already executed, which have used some of the dependent resources and those resources are still in use with the application executed, when another application or the same exe is triggered from some other source then one of the app throws the error
Scenario 2:
When an application is triggered by scheduler or automatic jobs, it may be in execution state at background, meanwhile when you try to trigger the same application again, the error may be triggered.
Solution:
Create an application, when & where the application release all its resources as soon as completed Kill all the background process once the application is closed Check and avoid executing the application from multiple sources like Batch Process, Task Scheduler and external tools at same time. Check for the Application and resource dependencies and clean up the code if needed.
EncodedParams variable is redefined as params variable will not work. You need to have same predefined call to variable, otherwise it looks possible with a little more work. Cheers! json is not used to its full capabilities in php there are better ways to call json which I don't recall at the moment.
add the dns entry to your system hosts file
for example:http://aaa.com/service.asmx?WSDL
you can get the aaa.com's ip address with ping
and then add to the hosts file
Why not make all functions inline by default? Because it's an engineering trade off. There are at least two types of "optimization": speeding up the program and reducing the size (memory footprint) of the program. Inlining generally speeds things up. It gets rid of the function call overhead, avoiding pushing then pulling parameters from the stack. However, it also makes the memory footprint of the program bigger, because every function call must now be replaced with the full code of the function. To make things even more complicated, remember that the CPU stores frequently used chunks of memory in a cache on the CPU for ultra-rapid access. If you make the program's memory image big enough, your program won't be able to use the cache efficiently, and in the worst case inlining could actually slow your program down. To some extent the compiler can calculate what the trade offs are, and may be able to make better decisions than you can, just looking at the source code.
This approach takes care of spaces within the values, but requires a loop:
#!/bin/bash
FOO=( a b c )
BAR=""
for index in ${!FOO[*]}
do
BAR="$BAR,${FOO[$index]}"
done
echo ${BAR:1}
To add jquery to laravel you first have to add the Scaffolded javascript file, app.js
This can easily be done adding this tag.
<script src="{{ asset('js/app.js') }}"></script>
There are two main procesess depending on the version but at the end of both you will have to execute:
npm run dev
That adds all the dependencies to the app.js file. But if you want this process to be done automatically for you, you can also run:
npm run watch
Wich will keep watching for changes and add them.
jQuery is already included in this version of laravel as a dev dependency.
You just have to run:
npm install
This first command will install the dependencies. jquery will be added.
jQuery has been taken out of laravel that means you need to import it manually.
I'll import it here as a development dependency:
npm i -D jquery
Then add it to the bootstrap.js file in resources/js/bootstrap.js You may notice that axios and lodash are imported there as well so in the same way we can import jquery.
Just add wherever you want there:
//In resources/js/bootstrap.js
window.$ = require('jquery');
If you follow this process in the 5.* version it won't affect laravel but it will install a more updated version of jquery.
This can be achieved with the onresize property of the GlobalEventHandlers interface in JavaScript, by assigning a function to the onresize property, like so:
window.onresize = functionRef;
The following code snippet demonstrates this, by console logging the innerWidth and innerHeight of the window whenever it's resized. (The resize event fires after the window has been resized)
function resize() {_x000D_
console.log("height: ", window.innerHeight, "px");_x000D_
console.log("width: ", window.innerWidth, "px");_x000D_
}_x000D_
_x000D_
window.onresize = resize;
_x000D_
<p>In order for this code snippet to work as intended, you will need to either shrink your browser window down to the size of this code snippet, or fullscreen this code snippet and resize from there.</p>
_x000D_
return new ResponseEntity<>(GenericResponseBean.newGenericError("Error during the calling the service", -1L), HttpStatus.EXPECTATION_FAILED);
def strip_end(text, suffix):
if suffix and text.endswith(suffix):
return text[:-len(suffix)]
return text
Use .closest()
, which gets the first ancestor element that matches the given selector 'div'
:
var classes = $(this).closest('div').attr('class').split(' ');
EDIT:
As @Shef noted, .closest()
will return the current element if it happens to be a DIV also. To take that into account, use .parent()
first:
var classes = $(this).parent().closest('div').attr('class').split(' ');
Handling %f and you should put
%.2f
, where: .2f == .00 floats.
Example:
print "Price: %.2f" % prices[product]
Price: 1.50
hi body very late but i am writing
if(mylist.contains(value)){}
No. JavaScript is a client-side technology and cannot do anything on the server. You could however use AJAX to call a server-side script (e.g. PHP) which could return the information you need.
If you want to use AJAX, the easiest way will be to utilise jQuery:
$.post("someScript.php", function(data) {
console.log(data); //"data" contains whatever someScript.php returned
});
There's also a practical programming issue with files lacking newlines at the end: The read
Bash built-in (I don't know about other read
implementations) doesn't work as expected:
printf $'foo\nbar' | while read line
do
echo $line
done
This prints only foo
! The reason is that when read
encounters the last line, it writes the contents to $line
but returns exit code 1 because it reached EOF. This breaks the while
loop, so we never reach the echo $line
part. If you want to handle this situation, you have to do the following:
while read line || [ -n "${line-}" ]
do
echo $line
done < <(printf $'foo\nbar')
That is, do the echo
if the read
failed because of a non-empty line at end of file. Naturally, in this case there will be one extra newline in the output which was not in the input.
It's known issue that passing shared_ptr by value has a cost and should be avoided if possible.
The cost of passing by shared_ptr
Most of the time passing shared_ptr by reference, and even better by const reference, would do.
The cpp core guideline has a specific rule for passing shared_ptr
R.34: Take a shared_ptr parameter to express that a function is part owner
void share(shared_ptr<widget>); // share -- "will" retain refcount
An example of when passing shared_ptr by value is really necessary is when the caller passes a shared object to an asynchronous callee - ie the caller goes out of scope before the callee completes its job. The callee must "extend" the lifetime of the shared object by taking a share_ptr by value. In this case, passing a reference to shared_ptr won't do.
The same goes for passing a shared object to a work thread.
I've seen this error too when the code stopped at the line:
Dim myNode As MSXML2.IXMLDOMNode
I found out that I had to add "Microsoft XML, v6.0" via Tools > Preferences.
Then it worked for me.
In simple words you can say:
1.HTTP Get:It is used to get one or more items
2.HTTP Post:It is used to create an item
3.HTTP Put:It is used to update an item
4.HTTP Patch:It is used to partially update an item
5.HTTP Delete:It is used to delete an item
Please try
sudo a2enmod rewrite
or use correct apache restart command
sudo /etc/init.d/apache2 restart
I want to put here some information for those, who do separately drawing of picture and moving -zooming it.
This may be useful when you want to store zooms and position of viewport.
Here is drawer:
function redraw_ctx(){
self.ctx.clearRect(0,0,canvas_width, canvas_height)
self.ctx.save()
self.ctx.scale(self.data.zoom, self.data.zoom) //
self.ctx.translate(self.data.position.left, self.data.position.top) // position second
// Here We draw useful scene My task - image:
self.ctx.drawImage(self.img ,0,0) // position 0,0 - we already prepared
self.ctx.restore(); // Restore!!!
}
Notice scale MUST be first.
And here is zoomer:
function zoom(zf, px, py){
// zf - is a zoom factor, which in my case was one of (0.1, -0.1)
// px, py coordinates - is point within canvas
// eg. px = evt.clientX - canvas.offset().left
// py = evt.clientY - canvas.offset().top
var z = self.data.zoom;
var x = self.data.position.left;
var y = self.data.position.top;
var nz = z + zf; // getting new zoom
var K = (z*z + z*zf) // putting some magic
var nx = x - ( (px*zf) / K );
var ny = y - ( (py*zf) / K);
self.data.position.left = nx; // renew positions
self.data.position.top = ny;
self.data.zoom = nz; // ... and zoom
self.redraw_ctx(); // redraw context
}
and, of course, we would need a dragger:
this.my_cont.mousemove(function(evt){
if (is_drag){
var cur_pos = {x: evt.clientX - off.left,
y: evt.clientY - off.top}
var diff = {x: cur_pos.x - old_pos.x,
y: cur_pos.y - old_pos.y}
self.data.position.left += (diff.x / self.data.zoom); // we want to move the point of cursor strictly
self.data.position.top += (diff.y / self.data.zoom);
old_pos = cur_pos;
self.redraw_ctx();
}
})
this solution it gonna be ok on Redhat 8.0
sudo yum install libxml2-devel
I would recommend using Offset
assuming that the Headers are in Row 1. See this example
Option Explicit
Sub Sample()
Dim rRange As Range, filRange As Range, Rng as Range
'Remove any filters
ActiveSheet.AutoFilterMode = False
'~~> Set your range
Set rRange = Sheets("Sheet1").Range("A1:E10")
With rRange
'~~> Set your criteria and filter
.AutoFilter Field:=1, Criteria1:="=1"
'~~> Filter, offset(to exclude headers)
Set filRange = .Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow
Debug.Print filRange.Address
For Each Rng In filRange
'~~> Your Code
Next
End With
'Remove any filters
ActiveSheet.AutoFilterMode = False
End Sub
SAP SE is a German multinational that makes enterprise software. It is best known for SAP ERP and its predecessors (SAP R/2 & SAP R/3). As the name suggests, SAP ERP is an ERP system, which basically means that it supports a wide range of business processes from warehouse management and sales to HR, business intelligence, etc.
Although SAP ERP isn't the only software sold by SAP, people are typically refering to SAP ERP when they say "they're using SAP at work". It's important to note, though, that SAP is the name of the company and no software is sold or licensed as just "SAP".
ABAP is a 4GL programming language created by SAP, and commonly compared with OpenEdge ABL or COBOL. Much of SAP's software is written in ABAP. SAP provides an ABAP Workbench, which is a collection of tools that allows third party developers to develop, test and run custom ABAP programs within the SAP ERP system. The ABAP Workbench is typically used only when business logic cannot be implemented in SAP ERP by means of mere configuration.
(tomcat 7.0.32) I had problems to see debug messages althought was enabling TldLocationsCache row in tomcat/conf/logging.properties file. All I could see was a warning but not what libs were scanned. Changed every loglevel tried everything no luck. Then I went rogue debug mode (=remove one by one, clean install etc..) and finally found a reason.
My webapp had a customized tomcat/webapps/mywebapp/WEB-INF/classes/logging.properties file. I copied TldLocationsCache row to this file, finally I could see jars filenames.
# To see debug messages in TldLocationsCache, uncomment the following line: org.apache.jasper.compiler.TldLocationsCache.level = FINE
I found the following working solution to pass onClick function argument from child to the parent component with param:
parent class :
class Parent extends React.Component {
constructor(props) {
super(props)
// Bind the this context to the handler function
this.handler = this.handler.bind(this);
// Set some state
this.state = {
messageShown: false
};
}
// This method will be sent to the child component
handler(param1) {
console.log(param1);
this.setState({
messageShown: true
});
}
// Render the child component and set the action property with the handler as value
render() {
return <Child action={this.handler} />
}}
child class :
class Child extends React.Component {
render() {
return (
<div>
{/* The button will execute the handler function set by the parent component */}
<Button onClick={this.props.action.bind(this,param1)} />
</div>
)
} }
The answer from Alexander refers to complete docs...
Your simple example from the question simply prints out these values with 2 digits - appending leading 0 if necessary.
None of the existing answers tell people how shutdown
and close
works at the TCP protocol level, so it is worth to add this.
A standard TCP connection gets terminated by 4-way finalization:
However, there is another "emergent" way to close a TCP connection:
In my test with Wireshark, with default socket options, shutdown
sends a FIN packet to the other end but it is all it does. Until the other party send you the FIN packet you are still able to receive data. Once this happened, your Receive
will get an 0 size result. So if you are the first one to shut down "send", you should close the socket once you finished receiving data.
On the other hand, if you call close
whilst the connection is still active (the other side is still active and you may have unsent data in the system buffer as well), an RST packet will be sent to the other side. This is good for errors. For example, if you think the other party provided wrong data or it refused to provide data (DOS attack?), you can close the socket straight away.
My opinion of rules would be:
shutdown
before close
when possibleIdeal implementations for SHUT_RD and SHUT_WR
The following haven't been tested, trust at your own risk. However, I believe this is a reasonable and practical way of doing things.
If the TCP stack receives a shutdown with SHUT_RD only, it shall mark this connection as no more data expected. Any pending and subsequent read
requests (regardless whichever thread they are in) will then returned with zero sized result. However, the connection is still active and usable -- you can still receive OOB data, for example. Also, the OS will drop any data it receives for this connection. But that is all, no packages will be sent to the other side.
If the TCP stack receives a shutdown with SHUT_WR only, it shall mark this connection as no more data can be sent. All pending write requests will be finished, but subsequent write requests will fail. Furthermore, a FIN packet will be sent to another side to inform them we don't have more data to send.
Hello...I have created a java client server application in swing for caesar cipher...I have created a new formula that can decrypt the text properly... sorry only for lower case..!
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.net.*;
import java.util.*;
public class ceasarserver extends JFrame implements ActionListener {
static String cs = "abcdefghijklmnopqrstuvwxyz";
static JLabel l1, l2, l3, l5, l6;
JTextField t1;
JButton close, b1;
static String en;
int num = 0;
JProgressBar progress;
ceasarserver() {
super("SERVER");
JPanel p = new JPanel(new GridLayout(10, 1));
l1 = new JLabel("");
l2 = new JLabel("");
l3 = new JLabel("");
l5 = new JLabel("");
l6 = new JLabel("Enter the Key...");
t1 = new JTextField(30);
progress = new JProgressBar(0, 20);
progress.setValue(0);
progress.setStringPainted(true);
close = new JButton("Close");
close.setMnemonic('C');
close.setPreferredSize(new Dimension(300, 25));
close.addActionListener(this);
b1 = new JButton("Decrypt");
b1.setMnemonic('D');
b1.addActionListener(this);
p.add(l1);
p.add(l2);
p.add(l3);
p.add(l6);
p.add(t1);
p.add(b1);
p.add(progress);
p.add(l5);
p.add(close);
add(p);
setVisible(true);
pack();
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == close)
System.exit(0);
else if (e.getSource() == b1) {
int key = Integer.parseInt(t1.getText());
String d = "";
int i = 0, j, k;
while (i < en.length()) {
j = cs.indexOf(en.charAt(i));
k = (j + (26 - key)) % 26;
d = d + cs.charAt(k);
i++;
}
while (num < 21) {
progress.setValue(num);
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
}
progress.setValue(num);
Rectangle progressRect = progress.getBounds();
progressRect.x = 0;
progressRect.y = 0;
progress.paintImmediately(progressRect);
num++;
}
l5.setText("Decrypted text: " + d);
}
}
public static void main(String args[]) throws IOException {
new ceasarserver();
String strm = new String();
ServerSocket ss = new ServerSocket(4321);
l1.setText("Secure data transfer Server Started....");
Socket s = ss.accept();
l2.setText("Client Connected !");
while (true) {
Scanner br1 = new Scanner(s.getInputStream());
en = br1.nextLine();
l3.setText("Client:" + en);
}
}
The client class:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.net.*;
import java.util.*;
public class ceasarclient extends JFrame {
String cs = "abcdefghijklmnopqrstuvwxyz";
static JLabel l1, l2, l3, l4, l5;
JButton b1, b2, b3;
JTextField t1, t2;
JProgressBar progress;
int num = 0;
String en = "";
ceasarclient(final Socket s) {
super("CLIENT");
JPanel p = new JPanel(new GridLayout(10, 1));
setSize(500, 500);
t1 = new JTextField(30);
b1 = new JButton("Send");
b1.setMnemonic('S');
b2 = new JButton("Close");
b2.setMnemonic('C');
l1 = new JLabel("Welcome to Secure Data transfer!");
l2 = new JLabel("Enter the word here...");
l3 = new JLabel("");
l4 = new JLabel("Enter the Key:");
b3 = new JButton("Encrypt");
b3.setMnemonic('E');
t2 = new JTextField(30);
progress = new JProgressBar(0, 20);
progress.setValue(0);
progress.setStringPainted(true);
p.add(l1);
p.add(l2);
p.add(t1);
p.add(l4);
p.add(t2);
p.add(b3);
p.add(progress);
p.add(b1);
p.add(l3);
p.add(b2);
add(p);
setVisible(true);
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
PrintWriter pw = new PrintWriter(s.getOutputStream(), true);
pw.println(en);
} catch (Exception ex) {
}
;
l3.setText("Encrypted Text Sent.");
}
});
b3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String strw = t1.getText();
int key = Integer.parseInt(t2.getText());
int i = 0, j, k;
while (i < strw.length()) {
j = cs.indexOf(strw.charAt(i));
k = (j + key) % 26;
en = en + cs.charAt(k);
i++;
}
while (num < 21) {
progress.setValue(num);
try {
Thread.sleep(100);
} catch (InterruptedException exe) {
}
progress.setValue(num);
Rectangle progressRect = progress.getBounds();
progressRect.x = 0;
progressRect.y = 0;
progress.paintImmediately(progressRect);
num++;
}
}
});
b2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
pack();
}
public static void main(String args[]) throws IOException {
final Socket s = new Socket(InetAddress.getLocalHost(), 4321);
new ceasarclient(s);
}
}
You are most likely not using the correct credentials for the MySQL server. You also need to ensure the user you are connecting as has the correct privileges to view databases/tables, and that you can connect from your current location in network topographic terms (localhost).
We're using Puma as a web server, and dotenv to set environment variables in development. This means I can set an environment variable for PORT
, and reference it in the Puma config.
# .env
PORT=10524
# config/puma.rb
port ENV['PORT']
However, you'll have to start your app with foreman start
instead of rails s
, otherwise the puma config doesn't get read properly.
I like this approach because the configuration works the same way in development and production, you just change the value of the port if necessary.
I have created some sample code which creates new variables using a variety of ways that I can think of. It looks like the first 3 ways create values, and the last two create references.
package main
import "fmt"
type Config struct {
host string
port float64
}
func main() {
//value
var c1 Config
c2 := Config{}
c3 := *new(Config)
//reference
c4 := &Config{}
c5 := new(Config)
fmt.Println(&c1 == nil)
fmt.Println(&c2 == nil)
fmt.Println(&c3 == nil)
fmt.Println(c4 == nil)
fmt.Println(c5 == nil)
fmt.Println(c1, c2, c3, c4, c5)
}
which outputs:
false
false
false
false
false
{ 0} { 0} { 0} &{ 0} &{ 0}
You could try giving an ID to the form, in order to get ahold of it, and then call form.submit() from a Javascript call.
Yes, ensure
ENSURES it is run every time, so you don't need the file.close
in the begin
block.
By the way, a good way to test is to do:
begin
# Raise an error here
raise "Error!!"
rescue
#handle the error here
ensure
p "=========inside ensure block"
end
You can test to see if "=========inside ensure block" will be printed out when there is an exception.
Then you can comment out the statement that raises the error and see if the ensure
statement is executed by seeing if anything gets printed out.
Combining dbenham's bird and syntax with skrebbel's powershell write-host
method, it seems that powershell can render complex art more quickly than dbenham's pure batch method (well, after powershell has been primed once, anyway). Minimal massaging of the strings are needed, although I haven't tested this with anything other than the bird. If you want a bright green end-of-transmission character for example, you may be out of luck. :)
This method requires echoing out to a temp file, simply because invoking powershell for each call :c
takes forever, and it's much faster to queue the output for one powershell invocation. But it does have the advantage of simplicity and efficiency.
@echo off
setlocal disableDelayedExpansion
set q=^"
echo(
echo(
call :c 0E " , .-;" /n
call :c 0E " , |\ / / __," /n
call :c 0E " |\ '.`-.| |.'.-'" /n
call :c 0E " \`'-: `; : /" /n
call :c 0E " `-._'. \'|" /n
call :c 0E " ,_.-=` ` ` ~,_" /n
call :c 0E " '--,. "&call :c 0c ".-. "&call :c 0E ",=!q!." /n
call :c 0E " / "&call :c 0c "{ "&call :c 0A "* "&call :c 0c ")"&call :c 0E "`"&call :c 06 ";-."&call :c 0E "}" /n
call :c 0E " | "&call :c 0c "'-' "&call :c 06 "/__ |" /n
call :c 0E " / "&call :c 06 "\_,\|" /n
call :c 0E " | (" /n
call :c 0E " "&call :c 0c "__ "&call :c 0E "/ ' \" /n
call :c 02 " /\_ "&call :c 0c "/,'`"&call :c 0E "| ' "&call :c 0c ".-~!q!~~-." /n
call :c 02 " |`.\_ "&call :c 0c "| "&call :c 0E "/ ' , "&call :c 0c "/ \" /n
call :c 02 " _/ `, \"&call :c 0c "| "&call :c 0E "; , . "&call :c 0c "| , ' . |" /n
call :c 02 " \ `, "&call :c 0c "| "&call :c 0E "| , , "&call :c 0c "| : ; : |" /n
call :c 02 " _\ `, "&call :c 0c "\ "&call :c 0E "|. , "&call :c 0c "| | | | |" /n
call :c 02 " \` `. "&call :c 0c "\ "&call :c 0E "| ' "&call :c 0A "|"&call :c 0c "\_|-'|_,'\|" /n
call :c 02 " _\ `, "&call :c 0A "`"&call :c 0E "\ ' . ' "&call :c 0A "| | | | | "&call :c 02 "__" /n
call :c 02 " \ `, "&call :c 0E "| , ' "&call :c 0A "|_/'-|_\_/ "&call :c 02 "__ ,-;` /" /n
call :c 02 " \ `, "&call :c 0E "\ . , ' .| | | | | "&call :c 02 "_/' ` _=`|" /n
call :c 02 " `\ `, "&call :c 0E "\ , | | | | |"&call :c 02 "_/' .=!q! /" /n
call :c 02 " \` `, "&call :c 0E "`\ \/|,| ;"&call :c 02 "/' .=!q! |" /n
call :c 02 " \ `, "&call :c 0E "`\' , | ; "&call :c 02 "/' =!q! _/" /n
call :c 02 " `\ `, "&call :c 05 ".-!q!!q!-. "&call :c 0E "': "&call :c 02 "/' =!q! /" /n
call :c 02 " jgs _`\ ;"&call :c 05 "_{ ' ; "&call :c 02 "/' =!q! /" /n
call :c 02 " _\`-/__"&call :c 05 ".~ `."&call :c 07 "8"&call :c 05 ".'.!q!`~-. "&call :c 02 "=!q! _,/" /n
call :c 02 " __\ "&call :c 05 "{ '-."&call :c 07 "|"&call :c 05 ".'.--~'`}"&call :c 02 " _/" /n
call :c 02 " \ .=!q!` "&call :c 05 "}.-~!q!'"&call :c 0D "u"&call :c 05 "'-. '-..' "&call :c 02 "__/" /n
call :c 02 " _/ .!q! "&call :c 05 "{ -'.~('-._,.'"&call :c 02 "\_,/" /n
call :c 02 " / .!q! _/'"&call :c 05 "`--; ; `. ;" /n
call :c 02 " .=!q! _/' "&call :c 05 "`-..__,-'" /n
call :c 02 " __/'" /n
if exist "%temp%\color.psm1" (
powershell -command "&{set-executionpolicy remotesigned; Import-Module '%temp%\color.psm1'}"
del "%temp%\color.psm1"
)
echo(
exit /b
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:c <color pair> <string> </n>
setlocal enabledelayedexpansion
set "colors=0-black;1-darkblue;2-darkgreen;3-darkcyan;4-darkred;5-darkmagenta;6-darkyellow;7-gray;8-darkgray;9-blue;a-green;b-cyan;c-red;d-magenta;e-yellow;f-white"
set "p=%~1"
set "bg=!colors:*%p:~0,1%-=!"
set bg=%bg:;=&rem.%
set "fg=!colors:*%p:~-1%-=!"
set fg=%fg:;=&rem.%
if not "%~3"=="/n" set "br=-nonewline"
set "str=%~2" & set "str=!str:'=''!"
>>"%temp%\color.psm1" echo write-host '!str!' -foregroundcolor '%fg%' -backgroundcolor '%bg%' %br%
endlocal
Result:
$('div#someDiv').removeAttr("height");
Inside your makefile:
target:
if test -d dir; then echo "hello world!"; else mkdir dir; fi
try:
gsub('\\$', '', '$5.00$')
I think 'git ls-remote' ( http://git-scm.com/docs/git-ls-remote ) should do what you want. Without force fetch or pull.
Necromancing.
YES YOU CAN, and this is how.
A secret tip for those migrating large junks chunks of code:
The following method is an evil carbuncle of a hack which is actively engaged in carrying out the express work of satan (in the eyes of .NET Core framework developers), but it works:
In public class Startup
add a property
public IConfigurationRoot Configuration { get; }
And then add a singleton IHttpContextAccessor to DI in ConfigureServices.
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<Microsoft.AspNetCore.Http.IHttpContextAccessor, Microsoft.AspNetCore.Http.HttpContextAccessor>();
Then in Configure
public void Configure(
IApplicationBuilder app
,IHostingEnvironment env
,ILoggerFactory loggerFactory
)
{
add the DI Parameter IServiceProvider svp
, so the method looks like:
public void Configure(
IApplicationBuilder app
,IHostingEnvironment env
,ILoggerFactory loggerFactory
,IServiceProvider svp)
{
Next, create a replacement class for System.Web:
namespace System.Web
{
namespace Hosting
{
public static class HostingEnvironment
{
public static bool m_IsHosted;
static HostingEnvironment()
{
m_IsHosted = false;
}
public static bool IsHosted
{
get
{
return m_IsHosted;
}
}
}
}
public static class HttpContext
{
public static IServiceProvider ServiceProvider;
static HttpContext()
{ }
public static Microsoft.AspNetCore.Http.HttpContext Current
{
get
{
// var factory2 = ServiceProvider.GetService<Microsoft.AspNetCore.Http.IHttpContextAccessor>();
object factory = ServiceProvider.GetService(typeof(Microsoft.AspNetCore.Http.IHttpContextAccessor));
// Microsoft.AspNetCore.Http.HttpContextAccessor fac =(Microsoft.AspNetCore.Http.HttpContextAccessor)factory;
Microsoft.AspNetCore.Http.HttpContext context = ((Microsoft.AspNetCore.Http.HttpContextAccessor)factory).HttpContext;
// context.Response.WriteAsync("Test");
return context;
}
}
} // End Class HttpContext
}
Now in Configure, where you added the IServiceProvider svp
, save this service provider into the static variable "ServiceProvider" in the just created dummy class System.Web.HttpContext (System.Web.HttpContext.ServiceProvider)
and set HostingEnvironment.IsHosted to true
System.Web.Hosting.HostingEnvironment.m_IsHosted = true;
this is essentially what System.Web did, just that you never saw it (I guess the variable was declared as internal instead of public).
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IServiceProvider svp)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
ServiceProvider = svp;
System.Web.HttpContext.ServiceProvider = svp;
System.Web.Hosting.HostingEnvironment.m_IsHosted = true;
app.UseCookieAuthentication(new CookieAuthenticationOptions()
{
AuthenticationScheme = "MyCookieMiddlewareInstance",
LoginPath = new Microsoft.AspNetCore.Http.PathString("/Account/Unauthorized/"),
AccessDeniedPath = new Microsoft.AspNetCore.Http.PathString("/Account/Forbidden/"),
AutomaticAuthenticate = true,
AutomaticChallenge = true,
CookieSecure = Microsoft.AspNetCore.Http.CookieSecurePolicy.SameAsRequest
, CookieHttpOnly=false
});
Like in ASP.NET Web-Forms, you'll get a NullReference when you're trying to access a HttpContext when there is none, such as it used to be in Application_Start
in global.asax.
I stress again, this only works if you actually added
services.AddSingleton<Microsoft.AspNetCore.Http.IHttpContextAccessor, Microsoft.AspNetCore.Http.HttpContextAccessor>();
like I wrote you should.
Welcome to the ServiceLocator pattern within the DI pattern ;)
For risks and side effects, ask your resident doctor or pharmacist - or study the sources of .NET Core at github.com/aspnet, and do some testing.
Perhaps a more maintainable method would be adding this helper class
namespace System.Web
{
public static class HttpContext
{
private static Microsoft.AspNetCore.Http.IHttpContextAccessor m_httpContextAccessor;
public static void Configure(Microsoft.AspNetCore.Http.IHttpContextAccessor httpContextAccessor)
{
m_httpContextAccessor = httpContextAccessor;
}
public static Microsoft.AspNetCore.Http.HttpContext Current
{
get
{
return m_httpContextAccessor.HttpContext;
}
}
}
}
And then calling HttpContext.Configure in Startup->Configure
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IServiceProvider svp)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
System.Web.HttpContext.Configure(app.ApplicationServices.
GetRequiredService<Microsoft.AspNetCore.Http.IHttpContextAccessor>()
);
You can try this
<select name="select1" onmousedown="if(this.options.length>8){this.size=8;}" onchange='this.size=0;' onblur="this.size=0;">_x000D_
<option value="1">This is select number 1</option>_x000D_
<option value="2">This is select number 2</option>_x000D_
<option value="3">This is select number 3</option>_x000D_
<option value="4">This is select number 4</option>_x000D_
<option value="5">This is select number 5</option>_x000D_
<option value="6">This is select number 6</option>_x000D_
<option value="7">This is select number 7</option>_x000D_
<option value="8">This is select number 8</option>_x000D_
<option value="9">This is select number 9</option>_x000D_
<option value="10">This is select number 10</option>_x000D_
<option value="11">This is select number 11</option>_x000D_
<option value="12">This is select number 12</option>_x000D_
</select>
_x000D_
It worked for me
The simplest solution would be a correlated sub select:
select
A.*
from
table_A A
where
A.id in (
select B.id from table_B B where B.tag = 'chair'
)
Alternatively you could join the tables and filter the rows you want:
select
A.*
from
table_A A
inner join table_B B
on A.id = B.id
where
B.tag = 'chair'
You should profile both and see which is faster on your dataset.
maybe your script tab has some problem.
if you set type, must type="application/javascript".
<!DOCTYPE html>
<html>
<head>
<title>
Hello
</title>
</head>
<body>
<div onclick="showMsg('Hello')">
Click me show message
</div>
<script type="application/javascript">
function showMsg(item) {
alert(item);
}
</script>
</body>
</html>
Database first and model first has no real differences. Generated code are the same and you can combine this approaches. For example, you can create database using designer, than you can alter database using sql script and update your model.
When you using code first you can't alter model without recreation database and losing all data. IMHO, this limitation is very strict and does not allow to use code first in production. For now it is not truly usable.
Second minor disadvantage of code first is that model builder require privileges on master database. This doesn't affect you if you using SQL Server Compact database or if you control database server.
Advantage of code first is very clean and simple code. You have full control of this code and can easily modify and use it as your view model.
I can recommend to use code first approach when you creating simple standalone application without versioning and using model\database first in projects that requires modification in production.
The database must have a name (example DB1), try this one:
OracleConnection con = new OracleConnection("data source=DB1;user id=fastecit;password=fastecit");
In case the TNS is not defined you can also try this one:
OracleConnection con = new OracleConnection("Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=DB1)));
User Id=fastecit;Password=fastecit");
Without using any API You can do something like this too by using pure CSS and Jquery Demo
HTML
<div class="pointer_tooltip">
Click & Drag to draw the area
</div>
CSS
.pointer_tooltip{
width : auto;
height : auto;
padding : 10px;
border-radius : 5px;
background-color : #fff;
position: absolute;
}
Jquery
$(document).mousemove(function( event ) {
var pageCoords = "( " + event.pageX + ", " + event.pageY + " )";
//set the actuall width
$('.pointer_tooltip').width($('.pointer_tooltip').width());
var position_top = event.pageY+18;
var position_left = event.pageX-60;
var width=$('body').width()-$('.pointer_tooltip').width();
//check if left not minus
if(position_left<0){
position_left=10;
}else if(position_left > width){
position_left=width-10;
}
$('.pointer_tooltip').css('top',position_top+'px');
$('.pointer_tooltip').css('left',position_left+'px');
});
One way to reduce rounding error is to use double rather than float. This won't make the problem go away, but it does reduce the amount of error in your program and float is almost never the best choice. IMHO.
UILabel *mycoollabel=[[UILabel alloc]initWithFrame:CGRectMake(10, 70, 50, 50)];
mycoollabel.text=@"I am cool";
// for multiple lines,if text lenght is long use next line
mycoollabel.numberOfLines=0;
[self.View addSubView:mycoollabel];
you can use preg_grep()
:
$a= array(
'one',
'two',
'three',
'four'
);
print_r( preg_grep( "/ONe/i" , $a ) );
In SQL Server direct division of two integer returns integer even if the result should be the float. There is an example below to get it across:
--1--
declare @weird_number_float float
set @weird_number_float=22/7
select @weird_number_float
--2--
declare @weird_number_decimal decimal(18,10)
set @weird_number_decimal=22/7
select @weird_number_decimal
--3--
declare @weird_number_numeric numeric
set @weird_number_numeric=22/7
select @weird_number_numeric
--Right way
declare @weird_number float
set @weird_number=cast(22 as float)/cast(7 as float)
select @weird_number
Just last block will return the 3,14285714285714. In spite of the second block defined with right precision the result will be 3.00000.
You can use the inbuilt readline
package, see docs here. I use stream to create a new output stream.
var fs = require('fs'),
readline = require('readline'),
stream = require('stream');
var instream = fs.createReadStream('/path/to/file');
var outstream = new stream;
outstream.readable = true;
outstream.writable = true;
var rl = readline.createInterface({
input: instream,
output: outstream,
terminal: false
});
rl.on('line', function(line) {
console.log(line);
//Do your stuff ...
//Then write to outstream
rl.write(cubestuff);
});
Large files will take some time to process. Do tell if it works.
Partially based on Mohsen's answer (the added first condition covers the case where the child is hidden before the parent):
jQuery.fn.isChildOverflowing = function (child) {
var p = jQuery(this).get(0);
var el = jQuery(child).get(0);
return (el.offsetTop < p.offsetTop || el.offsetLeft < p.offsetLeft) ||
(el.offsetTop + el.offsetHeight > p.offsetTop + p.offsetHeight || el.offsetLeft + el.offsetWidth > p.offsetLeft + p.offsetWidth);
};
Then just do:
jQuery('#parent').isChildOverflowing('#child');
It's quite Easy to show a Toast Message in Flutter.Scaffold.of(context).showSnackBar(SnackBar( content: Text("Toast Text Here"), ));
Run: python -c "import ssl; print(ssl.get_default_verify_paths())"
to check the current paths which are used to verify the certificate. Add your company's root certificate to one of those.
The path openssl_capath_env
points to the environment variable: SSL_CERT_DIR
.
If SSL_CERT_DIR
doesn't exist, you will need to create it and point it to a valid folder within your filesystem. You can then add your certificate to this folder to use it.
IMHO, fs.readFile()
should be avoided because it loads ALL the file in memory and it won't call the callback until all the file has been read.
The easiest way to read a text file is to read it line by line. I recommend a BufferedReader:
new BufferedReader ("file", { encoding: "utf8" })
.on ("error", function (error){
console.log ("error: " + error);
})
.on ("line", function (line){
console.log ("line: " + line);
})
.on ("end", function (){
console.log ("EOF");
})
.read ();
For complex data structures like .properties or json files you need to use a parser (internally it should also use a buffered reader).
Turns out all I needed to do was wrap the left-hand side of the expression in soft brackets:
<span class="gallery-date">{{(gallery.date | date:'mediumDate') || "Various"}}</span>
In Vue2, use v-bind.
Say I have an object for a poll
<div class="options" v-for="option in poll.body.options">
<div class="poll-item">
<label v-bind:for="option._id" v-bind:style="{color: option.color}">{{option.text}}</label>
<input type="radio" v-model="picked" v-bind:value="option._id" v-bind:id="option._id">
</div>
</div>
This worked for me:
Created __init__.py
file inside parent folder (in your case, inside site-packages
folder). And imported like this:
from site-packages.toolkit.interface import interface
Hope it will be useful for you as well !
If someone is using @Sceduled this might work for you.
@Scheduled(cron = "${name-of-the-cron:0 0/30 * * * ?}")
This worked for me.
New APC Admin interface have options to add/clear user cache and opcode cache, One interesting functionality is to add/refresh/delete directory's from opCode Cache
You can try this way:-
Give a class say header
to the header rows, use nextUntil to get all rows beneath the clicked header until the next header.
$('.header').click(function(){
$(this).nextUntil('tr.header').slideToggle(1000);
});
<table border="0">
<tr class="header">
<td colspan="2">Header</td>
</tr>
<tr>
<td>data</td>
<td>data</td>
</tr>
<tr>
<td>data</td>
<td>data</td>
</tr>
Another Example:
$('.header').click(function(){
$(this).find('span').text(function(_, value){return value=='-'?'+':'-'});
$(this).nextUntil('tr.header').slideToggle(100); // or just use "toggle()"
});
You can also use promise to toggle the span icon/text after the toggle is complete in-case of animated toggle.
$('.header').click(function () {
var $this = $(this);
$(this).nextUntil('tr.header').slideToggle(100).promise().done(function () {
$this.find('span').text(function (_, value) {
return value == '-' ? '+' : '-'
});
});
});
Or just with a css pseudo element to represent the sign of expansion/collapse, and just toggle a class on the header.
CSS:-
.header .sign:after{
content:"+";
display:inline-block;
}
.header.expand .sign:after{
content:"-";
}
JS:-
$(this).toggleClass('expand').nextUntil('tr.header').slideToggle(100);
I second @erickson: The pure data-transfer speed penalty is negligible. Modern CPUs reach a crypto/AES throughput of several hundred MBit/s. So unless you are on resource constrained system (mobile phone) TLS/SSL is fast enough for slinging data around.
But keep in mind that encryption makes caching and load balancing much harder. This might result in a huge performance penalty.
But connection setup is really a show stopper for many application. On low bandwidth, high packet loss, high latency connections (mobile device in the countryside) the additional roundtrips required by TLS might render something slow into something unusable.
For example we had to drop the encryption requirement for access to some of our internal web apps - they where next to unusable if used from china.
If you are on a OS X, this probably has nothing to do with the sed command. On the OSX version of sed
, the -i
option expects an extension
argument so your command is actually parsed as the extension
argument and the file path is interpreted as the command code.
Try adding the -e
argument explicitly and giving ''
as argument to -i
:
find ./ -type f -exec sed -i '' -e "s/192.168.20.1/new.domain.com/" {} \;
See this.
More Details Visit https://github.com/sapankumarmohanty/lamp/blob/master/Crate-XML-2-Array
//Convert XML to array and SOAP XML to array
function xml2array($contents, $get_attributes = 1, $priority = 'tag')
{
if (!$contents) return array();
if (!function_exists('xml_parser_create')) {
// print "'xml_parser_create()' function not found!";
return array();
}
// Get the XML parser of PHP - PHP must have this module for the parser to work
$parser = xml_parser_create('');
xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, "UTF-8"); // http://minutillo.com/steve/weblog/2004/6/17/php-xml-and-character-encodings-a-tale-of-sadness-rage-and-data-loss
xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
xml_parse_into_struct($parser, trim($contents) , $xml_values);
xml_parser_free($parser);
if (!$xml_values) return; //Hmm...
// Initializations
$xml_array = array();
$parents = array();
$opened_tags = array();
$arr = array();
$current = & $xml_array; //Refference
// Go through the tags.
$repeated_tag_index = array(); //Multiple tags with same name will be turned into an array
foreach($xml_values as $data) {
unset($attributes, $value); //Remove existing values, or there will be trouble
// This command will extract these variables into the foreach scope
// tag(string), type(string), level(int), attributes(array).
extract($data); //We could use the array by itself, but this cooler.
$result = array();
$attributes_data = array();
if (isset($value)) {
if ($priority == 'tag') $result = $value;
else $result['value'] = $value; //Put the value in a assoc array if we are in the 'Attribute' mode
}
// Set the attributes too.
if (isset($attributes) and $get_attributes) {
foreach($attributes as $attr => $val) {
if ( $attr == 'ResStatus' ) {
$current[$attr][] = $val;
}
if ($priority == 'tag') $attributes_data[$attr] = $val;
else $result['attr'][$attr] = $val; //Set all the attributes in a array called 'attr'
}
}
// See tag status and do the needed.
//echo"<br/> Type:".$type;
if ($type == "open") { //The starting of the tag '<tag>'
$parent[$level - 1] = & $current;
if (!is_array($current) or (!in_array($tag, array_keys($current)))) { //Insert New tag
$current[$tag] = $result;
if ($attributes_data) $current[$tag . '_attr'] = $attributes_data;
//print_r($current[$tag . '_attr']);
$repeated_tag_index[$tag . '_' . $level] = 1;
$current = & $current[$tag];
}
else { //There was another element with the same tag name
if (isset($current[$tag][0])) { //If there is a 0th element it is already an array
$current[$tag][$repeated_tag_index[$tag . '_' . $level]] = $result;
$repeated_tag_index[$tag . '_' . $level]++;
}
else { //This section will make the value an array if multiple tags with the same name appear together
$current[$tag] = array(
$current[$tag],
$result
); //This will combine the existing item and the new item together to make an array
$repeated_tag_index[$tag . '_' . $level] = 2;
if (isset($current[$tag . '_attr'])) { //The attribute of the last(0th) tag must be moved as well
$current[$tag]['0_attr'] = $current[$tag . '_attr'];
unset($current[$tag . '_attr']);
}
}
$last_item_index = $repeated_tag_index[$tag . '_' . $level] - 1;
$current = & $current[$tag][$last_item_index];
}
}
elseif ($type == "complete") { //Tags that ends in 1 line '<tag />'
// See if the key is already taken.
if (!isset($current[$tag])) { //New Key
$current[$tag] = $result;
$repeated_tag_index[$tag . '_' . $level] = 1;
if ($priority == 'tag' and $attributes_data) $current[$tag . '_attr'] = $attributes_data;
}
else { //If taken, put all things inside a list(array)
if (isset($current[$tag][0]) and is_array($current[$tag])) { //If it is already an array...
// ...push the new element into that array.
$current[$tag][$repeated_tag_index[$tag . '_' . $level]] = $result;
if ($priority == 'tag' and $get_attributes and $attributes_data) {
$current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data;
}
$repeated_tag_index[$tag . '_' . $level]++;
}
else { //If it is not an array...
$current[$tag] = array(
$current[$tag],
$result
); //...Make it an array using using the existing value and the new value
$repeated_tag_index[$tag . '_' . $level] = 1;
if ($priority == 'tag' and $get_attributes) {
if (isset($current[$tag . '_attr'])) { //The attribute of the last(0th) tag must be moved as well
$current[$tag]['0_attr'] = $current[$tag . '_attr'];
unset($current[$tag . '_attr']);
}
if ($attributes_data) {
$current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data;
}
}
$repeated_tag_index[$tag . '_' . $level]++; //0 and 1 index is already taken
}
}
}
elseif ($type == 'close') { //End of tag '</tag>'
$current = & $parent[$level - 1];
}
}
return ($xml_array);
}
// Let's call the this above function xml2array
xml2array($xmlContent, $get_attributes = 3, $priority = 'tag'); // it will work 100% if not ping me @skype: sapan.mohannty
// Enjoy coding
No, you can't use sizeof(ptr)
to find the size of array ptr
is pointing to.
Though allocating extra memory(more than the size of array) will be helpful if you want to store the length in extra space.
This is for until IE9
<!--[if IE ]>
<style> .someclass{
text-align: center;
background: #00ADEF;
color: #fff;
visibility:hidden; // in case of hiding
}
#someotherclass{
display: block !important;
visibility:visible; // in case of visible
}
</style>
This is for after IE9
@media screen and (-ms-high-contrast: active), (-ms-high-contrast: none) {enter your CSS here}
Using Process.Start
on explorer.exe
with the /select
argument oddly only works for paths less than 120 characters long.
I had to use a native windows method to get it to work in all cases:
[DllImport("shell32.dll", SetLastError = true)]
public static extern int SHOpenFolderAndSelectItems(IntPtr pidlFolder, uint cidl, [In, MarshalAs(UnmanagedType.LPArray)] IntPtr[] apidl, uint dwFlags);
[DllImport("shell32.dll", SetLastError = true)]
public static extern void SHParseDisplayName([MarshalAs(UnmanagedType.LPWStr)] string name, IntPtr bindingContext, [Out] out IntPtr pidl, uint sfgaoIn, [Out] out uint psfgaoOut);
public static void OpenFolderAndSelectItem(string folderPath, string file)
{
IntPtr nativeFolder;
uint psfgaoOut;
SHParseDisplayName(folderPath, IntPtr.Zero, out nativeFolder, 0, out psfgaoOut);
if (nativeFolder == IntPtr.Zero)
{
// Log error, can't find folder
return;
}
IntPtr nativeFile;
SHParseDisplayName(Path.Combine(folderPath, file), IntPtr.Zero, out nativeFile, 0, out psfgaoOut);
IntPtr[] fileArray;
if (nativeFile == IntPtr.Zero)
{
// Open the folder without the file selected if we can't find the file
fileArray = new IntPtr[0];
}
else
{
fileArray = new IntPtr[] { nativeFile };
}
SHOpenFolderAndSelectItems(nativeFolder, (uint)fileArray.Length, fileArray, 0);
Marshal.FreeCoTaskMem(nativeFolder);
if (nativeFile != IntPtr.Zero)
{
Marshal.FreeCoTaskMem(nativeFile);
}
}
You can use the 're' module in Python 3.
If you indeed do, use this:
re.search('\s', word)
This should return either 'true' if there's a match, or 'false' if there isn't any.
If attempting to download via the App Store leaves you with a little grey spinner and nothing actually happening, then you can go to :
log in with your Apple Developer ID, and the latest Xcode should be available as a .zip download.
Table lookup or
uint8_t rev_byte(uint8_t x) {
uint8_t y;
uint8_t m = 1;
while (m) {
y >>= 1;
if (m&x) {
y |= 0x80;
}
m <<=1;
}
return y;
}
edit
Look here for other solutions that might work better for you
>>> s = pd.Series([1,2,3,4,np.NaN,5,np.NaN])
>>> s[~s.isnull()]
0 1
1 2
2 3
3 4
5 5
update or even better approach as @DSM suggested in comments, using pandas.Series.dropna()
:
>>> s.dropna()
0 1
1 2
2 3
3 4
5 5
Install Both of the below links
Note: (For Vista and Windows Server 2008 >>> Windows6.0 and For Windows 7 and Windows Server 2008 R2, >>> Windows6.1. )
Windows Identity Foundation SDK
Note: Download the 3.5 version for Visual Studio 2008 and .NET 3.5, the 4.0 version for Visual Studio 2010 and .NET 4.0.
Then Only, You will able to get the assembly called Microsoft.IdentityModel
The following tip isn't an answer to this thread's original question, but might help some other users who end up on this webpage, after making the same stupid mistake I just did...
I was attempting to get an ASP.Net FileUpload control to upload it's file to a network address which contained a "hidden share", namely:
\MyNetworkServer\c$\SomeDirectoryOrOther
I didn't understand it. If I ran the webpage in Debug mode in Visual Studio, it'd work fine. But when the project was deployed, and was running via an Application Pool user, it refused to find this network directory.
I had checked which user my IIS site was running under, gave this user full permissions to this directory on the "MyNetworkServer" server, etc etc, but nothing worked.
The reason (of course!) is that only Administrators are able to "see" these hidden drive shares.
My solution was simply to create a "normal" share to
\MyNetworkServer\SomeDirectoryOrOther
and this got rid of the "Access to the path... is denied" error. The FileUpload was able to successfully run the command
fileUpload.SaveAs(networkFilename);
Hope this helps some other users who make the same mistake I did !
Note also that if you're uploading large files (over 4Mb), then IIS7 requires that you modify the web.config file in two places. Click on this link to read what you need to do: Uploading large files in ASP.Net
You can use a third party library, such as PSI:
PSI is a Python package providing real-time access to processes and other miscellaneous system information such as architecture, boottime and filesystems. It has a pythonic API which is consistent accross all supported platforms but also exposes platform-specific details where desirable.
I've wrote my simple method for it :
public class SomeCommons {
/** Message Format like 'Some String {0} / {1}' with arguments */
public static String msgFormat(String s, Object... args) {
return new MessageFormat(s).format(args);
}
}
so you can use it as:
SomeCommons.msfgFormat("Step {1} of {2}", 1 , "two");
I faced a similar problem in Eclipse. Whenever I clicked on the Run button it gave me the message, "Error: Could not find or load main class". But when I right click on the java file in the project explorer and Run As Java configuration, it works perfectly.
I think this is because it tries by default to run it in some other configuration which causes problems.
Hope this answer helps some.
You have used:
char s[] = "asd";
Here s actually points to the bytes "asd". The address of s, would also point to this location.
If you used:
char *s = "asd";
the value of s and &s would be different, as s would actually be a pointer to the bytes "asd".
You used:
char s[] = "asd";
char **p = &s;
Here s points to the bytes "asd". p is a pointer to a pointer to characters, and has been set to a the address of characters. In other words you have too many indirections in p. If you used char *s = "asd", you could use this additional indirection.
In later versions (tested with TensorFlow 1.14) there's a more numpy-like way to get the shape of a tensor. You can use tensor.shape
to get the shape of the tensor.
tensor_shape = tensor.shape
print(tensor_shape)
Things to try:
ping 8.8.8.8
ping www.google.com
ping registry.npmjs.org
Try in your browser: https://registry.npmjs.org/
Make sure you are trying to connect to:
registry.npmjs.org
and not to:
"registry.npmjs.org registry.npmjs.org:443"
or some other weird string composed of few hostnames, because it's weird that the resolver complains about a hostnames that includes a port number, which it shouldn't care about. Ok, I tested and it should look like this for hosts that are not found.
From your comment to this answer it seems that you are not directly connected to the internet if you can't even ping 8.8.8.8.
If you are using a proxy to access the Web, then you also have to configure npm
to use it. Use:
npm config set proxy http://example.com:8080
npm config set https-proxy http://example.com:8080
but instead of http://example.com:8080
use what you actually need in your company - ask someone or see how your browser is configured.
To see your proxy configuration in Chrome, see this.
If you can access https://registry.npmjs.org/ in your browser but you cannot run ping registry.npmjs.org
then it means that your browser must be configured to use a proxy, or other programs than your browser must be restricted from using the internet.
In any case, you should ask someone in your company about it because most likely you either need to use a specific proxy or someone needs to lift the restriction from your npm
and allow it to access the network.
The network access can be blocked by a firewall installed on your computer or a router in your network. It's hard to say without knowing the specific configuration in your company.
Remove the environment variable "https_proxy" if any or use correct value for "https_proxy"
show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| datapass_schema |
| mysql |
| test |
+--------------------+
4 rows in set (0.05 sec)
mysql> use mysql;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Database changed
mysql> show tables
-> ;
+---------------------------+
| Tables_in_mysql |
+---------------------------+
| columns_priv |
| db |
| event |
| func |
| general_log |
| help_category |
| help_keyword |
| help_relation |
| help_topic |
| host |
| ndb_binlog_index |
| plugin |
| proc |
| procs_priv |
| servers |
| slow_log |
| tables_priv |
| time_zone |
| time_zone_leap_second |
| time_zone_name |
| time_zone_transition |
| time_zone_transition_type |
| user |
+---------------------------+
23 rows in set (0.00 sec)
mysql> create user m identified by 'm';
Query OK, 0 rows affected (0.02 sec)
check for the database mysql and table user as shown above if that dosent work, your mysql installation is not proper.
use the below command as mention in other post to install tables again
mysql_install_db
Anyway, I was following my workflow on a recent branch, and when I tried to merge it back to master, it all went to hell. There were tons of conflicts with things that should have not mattered. The conflicts just made no sense to me. It took me a day to sort everything out, and eventually culminated in a forced push to the remote master, since my local master has all conflicts resolved, but the remote one still wasn't happy.
In neither your partner's nor your suggested workflows should you have come across conflicts that didn't make sense. Even if you had, if you are following the suggested workflows then after resolution a 'forced' push should not be required. It suggests that you haven't actually merged the branch to which you were pushing, but have had to push a branch that wasn't a descendent of the remote tip.
I think you need to look carefully at what happened. Could someone else have (deliberately or not) rewound the remote master branch between your creation of the local branch and the point at which you attempted to merge it back into the local branch?
Compared to many other version control systems I've found that using Git involves less fighting the tool and allows you to get to work on the problems that are fundamental to your source streams. Git doesn't perform magic, so conflicting changes cause conflicts, but it should make it easy to do the write thing by its tracking of commit parentage.
You don't need to use sed
to do a substitution when in actual fact, you just want to insert a tab in front of the line. Substitution for this case is an expensive operation as compared to just printing it out, especially when you are working with big files. Its easier to read too as its not regex.
eg using awk
awk '{print "\t"$0}' $filename > temp && mv temp $filename
Very late to the party on this one, but I wrote the following helper class recently for a project at work. It was designed to convert short strings into numbers and back again (a simplistic perfect hash function), however it will also perform number conversion between arbitrary bases. The Base10ToString
method implementation answers the question that was originally posted.
The shouldSupportRoundTripping
flag passed to the class constructor is needed to prevent the loss of leading digits from the number string during conversion to base-10 and back again (crucial, given my requirements!). Most of the time the loss of leading 0s from the number string probably won't be an issue.
Anyway, here's the code:
using System;
using System.Collections.Generic;
using System.Linq;
namespace StackOverflow
{
/// <summary>
/// Contains methods used to convert numbers between base-10 and another numbering system.
/// </summary>
/// <remarks>
/// <para>
/// This conversion class makes use of a set of characters that represent the digits used by the target
/// numbering system. For example, binary would use the digits 0 and 1, whereas hex would use the digits
/// 0 through 9 plus A through F. The digits do not have to be numerals.
/// </para>
/// <para>
/// The first digit in the sequence has special significance. If the number passed to the
/// <see cref="StringToBase10"/> method has leading digits that match the first digit, then those leading
/// digits will effectively be 'lost' during conversion. Much of the time this won't matter. For example,
/// "0F" hex will be converted to 15 decimal, but when converted back to hex it will become simply "F",
/// losing the leading "0". However, if the set of digits was A through Z, and the number "ABC" was
/// converted to base-10 and back again, then the leading "A" would be lost. The <see cref="System.Boolean"/>
/// flag passed to the constructor allows 'round-tripping' behaviour to be supported, which will prevent
/// leading digits from being lost during conversion.
/// </para>
/// <para>
/// Note that numeric overflow is probable when using longer strings and larger digit sets.
/// </para>
/// </remarks>
public class Base10Converter
{
const char NullDigit = '\0';
public Base10Converter(string digits, bool shouldSupportRoundTripping = false)
: this(digits.ToCharArray(), shouldSupportRoundTripping)
{
}
public Base10Converter(IEnumerable<char> digits, bool shouldSupportRoundTripping = false)
{
if (digits == null)
{
throw new ArgumentNullException("digits");
}
if (digits.Count() == 0)
{
throw new ArgumentException(
message: "The sequence is empty.",
paramName: "digits"
);
}
if (!digits.Distinct().SequenceEqual(digits))
{
throw new ArgumentException(
message: "There are duplicate characters in the sequence.",
paramName: "digits"
);
}
if (shouldSupportRoundTripping)
{
digits = (new[] { NullDigit }).Concat(digits);
}
_digitToIndexMap =
digits
.Select((digit, index) => new { digit, index })
.ToDictionary(keySelector: x => x.digit, elementSelector: x => x.index);
_radix = _digitToIndexMap.Count;
_indexToDigitMap =
_digitToIndexMap
.ToDictionary(keySelector: x => x.Value, elementSelector: x => x.Key);
}
readonly Dictionary<char, int> _digitToIndexMap;
readonly Dictionary<int, char> _indexToDigitMap;
readonly int _radix;
public long StringToBase10(string number)
{
Func<char, int, long> selector =
(c, i) =>
{
int power = number.Length - i - 1;
int digitIndex;
if (!_digitToIndexMap.TryGetValue(c, out digitIndex))
{
throw new ArgumentException(
message: String.Format("Number contains an invalid digit '{0}' at position {1}.", c, i),
paramName: "number"
);
}
return Convert.ToInt64(digitIndex * Math.Pow(_radix, power));
};
return number.Select(selector).Sum();
}
public string Base10ToString(long number)
{
if (number < 0)
{
throw new ArgumentOutOfRangeException(
message: "Value cannot be negative.",
paramName: "number"
);
}
string text = string.Empty;
long remainder;
do
{
number = Math.DivRem(number, _radix, out remainder);
char digit;
if (!_indexToDigitMap.TryGetValue((int) remainder, out digit) || digit == NullDigit)
{
throw new ArgumentException(
message: "Value cannot be converted given the set of digits used by this converter.",
paramName: "number"
);
}
text = digit + text;
}
while (number > 0);
return text;
}
}
}
This can also be subclassed to derive custom number converters:
namespace StackOverflow
{
public sealed class BinaryNumberConverter : Base10Converter
{
public BinaryNumberConverter()
: base(digits: "01", shouldSupportRoundTripping: false)
{
}
}
public sealed class HexNumberConverter : Base10Converter
{
public HexNumberConverter()
: base(digits: "0123456789ABCDEF", shouldSupportRoundTripping: false)
{
}
}
}
And the code would be used like this:
using System.Diagnostics;
namespace StackOverflow
{
class Program
{
static void Main(string[] args)
{
{
var converter = new Base10Converter(
digits: "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz",
shouldSupportRoundTripping: true
);
long number = converter.StringToBase10("Atoz");
string text = converter.Base10ToString(number);
Debug.Assert(text == "Atoz");
}
{
var converter = new HexNumberConverter();
string text = converter.Base10ToString(255);
long number = converter.StringToBase10(text);
Debug.Assert(number == 255);
}
}
}
}