You can use the workbook.get_worksheet_by_name() feature: https://xlsxwriter.readthedocs.io/workbook.html#get_worksheet_by_name
According to https://xlsxwriter.readthedocs.io/changes.html the feature has been added on May 13, 2016.
"Release 0.8.7 - May 13 2016
-Fix for issue when inserting read-only images on Windows. Issue #352.
-Added get_worksheet_by_name() method to allow the retrieval of a worksheet from a workbook via its name.
-Fixed issue where internal file creation and modification dates were in the local timezone instead of UTC."
I had a similar problem application-level add-in in VSTO, the exception HRESULT: 0x800A03EC when adding new sheet.
The error code 0x800A03EC (or -2146827284) means NAME_NOT_FOUND; in other words, you've asked for something, and Excel can't find it.
Dominic Zukiewicz @ Excel error HRESULT: 0x800A03EC while trying to get range with cell's name
Then I finally realized ThisWorkbook triggered the exception. ActiveWorkbook went OK.
Excel.Worksheet newSheetException = Globals.ThisAddIn.Application.ThisWorkbook.Worksheets.Add(Type.Missing, sheet, Type.Missing, Type.Missing);
Excel.Worksheet newSheetNoException = Globals.ThisAddIn.Application.ActiveWorkbook.Worksheets.Add(Type.Missing, sheet, Type.Missing, Type.Missing);
In the Excel object model a Worksheet has 2 different name properties:
Worksheet.Name
Worksheet.CodeName
the Name property is read/write and contains the name that appears on the sheet tab. It is user and VBA changeable
the CodeName property is read-only
You can reference a particular sheet as Worksheets("Fred").Range("A1") where Fred is the .Name property or as Sheet1.Range("A1") where Sheet1 is the codename of the worksheet.
Try this:
Public Enum iSide
iBefore
iAfter
End Enum
Private Function addSheet(ByRef inWB As Workbook, ByVal inBeforeOrAfter As iSide, ByRef inNamePrefix As String, ByVal inName As String) As Worksheet
On Error GoTo the_dark
Dim wsSheet As Worksheet
Dim bFoundWS As Boolean
bFoundWS = False
If inNamePrefix <> "" Then
Set wsSheet = findWS(inWB, inNamePrefix, bFoundWS)
End If
If inBeforeOrAfter = iAfter Then
If wsSheet Is Nothing Or bFoundWS = False Then
Worksheets.Add(After:=Worksheets(Worksheets.Count)).Name = inName
Else
Worksheets.Add(After:=wsSheet).Name = inName
End If
Else
If wsSheet Is Nothing Or bFoundWS = False Then
Worksheets.Add(Before:=Worksheets(1)).Name = inName
Else
Worksheets.Add(Before:=wsSheet).Name = inName
End If
End If
Set addSheet = findWS(inWB, inName, bFoundWS) ' just to confirm it exists and gets it handle
the_light:
Exit Function
the_dark:
MsgBox "addSheet: " & inName & ": " & Err.Description, vbOKOnly, "unexpected error"
Err.Clear
GoTo the_light
End Function
The best way is to create a variable of type Worksheet
, assign the worksheet and use it every time the VBA would implicitly use the ActiveSheet
.
This will help you avoid bugs that will eventually show up when your program grows in size.
For example something like Range("A1:C10").Sort Key1:=Range("A2")
is good when the macro works only on one sheet. But you will eventually expand your macro to work with several sheets, find out that this doesn't work, adjust it to ShTest1.Range("A1:C10").Sort Key1:=Range("A2")
... and find out that it still doesn't work.
Here is the correct way:
Dim ShTest1 As Worksheet
Set ShTest1 = Sheets("Test1")
ShTest1.Range("A1:C10").Sort Key1:=ShTest1.Range("A2")
Try this more succinct code:
Sub LoopOverEachColumn()
Dim WS As Worksheet
For Each WS In ThisWorkbook.Worksheets
ResizeColumns WS
Next WS
End Sub
Private Sub ResizeColumns(WS As Worksheet)
Dim StrSize As String
Dim ColIter As Long
StrSize = "20.14;9.71;35.86;30.57;23.57;21.43;18.43;23.86;27.43;36.71;30.29;31.14;31;41.14;33.86"
For ColIter = 1 To 15
WS.Columns(ColIter).ColumnWidth = Split(StrSize, ";")(ColIter - 1)
Next ColIter
End Sub
If you want additional columns, just change 1 to 15
to 1 to X
where X
is the column index of the column you want, and append the column size you want to StrSize
.
For example, if you want P:P
to have a width of 25
, just add ;25
to StrSize
and change ColIter...
to ColIter = 1 to 16
.
Hope this helps.
Here's another solution that uses some of VBA's built in date functions and stores all the date data in an array for comparison, which may give better performance if you get a lot of data:
Public Sub MoveData(MonthNum As Integer, FromSheet As Worksheet, ToSheet As Worksheet)
Const DateCol = "A" 'column where dates are store
Const DestCol = "A" 'destination column where dates are stored. We use this column to find the last populated row in ToSheet
Const FirstRow = 2 'first row where date data is stored
'Copy range of values to Dates array
Dates = FromSheet.Range(DateCol & CStr(FirstRow) & ":" & DateCol & CStr(FromSheet.Range(DateCol & CStr(FromSheet.Rows.Count)).End(xlUp).Row)).Value
Dim i As Integer
For i = LBound(Dates) To UBound(Dates)
If IsDate(Dates(i, 1)) Then
If Month(CDate(Dates(i, 1))) = MonthNum Then
Dim CurrRow As Long
'get the current row number in the worksheet
CurrRow = FirstRow + i - 1
Dim DestRow As Long
'get the destination row
DestRow = ToSheet.Range(DestCol & CStr(ToSheet.Rows.Count)).End(xlUp).Row + 1
'copy row CurrRow in FromSheet to row DestRow in ToSheet
FromSheet.Range(CStr(CurrRow) & ":" & CStr(CurrRow)).Copy ToSheet.Range(DestCol & CStr(DestRow))
End If
End If
Next i
End Sub
Above two answers are correct but didn't work for me.
docker container ls
docker container ls -a
and after that it showed all the process previously exited and running.docker stop <container id>
or docker container stop <container id>
didn't work docker rm -f <container id>
and it worked.docker container ls -a
and this process wasn't present.As far as how to use unwind segues in StoryBoard...
Step 1)
Go to the code for the view controller that you wish to unwind to and add this:
Objective-C
- (IBAction)unwindToViewControllerNameHere:(UIStoryboardSegue *)segue {
//nothing goes here
}
Be sure to also declare this method in your .h file in Obj-C
Swift
@IBAction func unwindToViewControllerNameHere(segue: UIStoryboardSegue) {
//nothing goes here
}
Step 2)
In storyboard, go to the view that you want to unwind from and simply drag a segue from your button or whatever up to the little orange "EXIT" icon at the top right of your source view.
There should now be an option to connect to "- unwindToViewControllerNameHere"
That's it, your segue will unwind when your button is tapped.
in python sorted
works like you want with integers:
>>> sorted([10,3,2])
[2, 3, 10]
it looks like you have a problem because you are using strings:
>>> sorted(['10','3','2'])
['10', '2', '3']
(because string ordering starts with the first character, and "1" comes before "2", no matter what characters follow) which can be fixed with key=int
>>> sorted(['10','3','2'], key=int)
['2', '3', '10']
which converts the values to integers during the sort (it is called as a function - int('10')
returns the integer 10
)
and as suggested in the comments, you can also sort the list itself, rather than generating a new one:
>>> l = ['10','3','2']
>>> l.sort(key=int)
>>> l
['2', '3', '10']
but i would look into why you have strings at all. you should be able to save and retrieve integers. it looks like you are saving a string when you should be saving an int? (sqlite is unusual amongst databases, in that it kind-of stores data in the same type as it is given, even if the table column type is different).
and once you start saving integers, you can also get the list back sorted from sqlite by adding order by ...
to the sql command:
select temperature from temperatures order by temperature;
Dim r As Range
Set
sets the variable to an object reference.
Set r = Range("A1")
However, I don't think this is what you're really asking.
Sometimes I use:
Dim r as Range r = Range("A1")
This will never work. Without Set
you will receive runtime error #91 Object variable or With block variable not set. This is because you must use Set
to assign a variables value to an object reference. Then the code above will work.
I think the code below illustrates what you're really asking about. Let's suppose we don't declare a type and let r
be a Variant
type instead.
Public Sub test()
Dim r
debug.print TypeName(r)
Set r = Range("A1")
debug.print TypeName(r)
r = Range("A1")
debug.print TypeName(r)
End Sub
So, let's break down what happens here.
r
is declared as a Variant
`Dim r` ' TypeName(r) returns "Empty", which is the value for an uninitialized variant
r
is set to the Range
containing cell "A1"
Set r = Range("A1") ' TypeName(r) returns "Range"
r
is set to the value of the default property of Range("A1")
.
r = Range("A1") ' TypeName(r) returns "String"
In this case, the default property of a Range is .Value
, so the following two lines of code are equivalent.
r = Range("A1")
r = Range("A1").Value
For more about default object properties, please see Chip Pearson's "Default Member of a Class".
As for your Set
example:
Other times I use
Set r = Range("A1")
This wouldn't work without first declaring that r
is a Range
or Variant
object... using the Dim
statement - unless you don't have Option Explicit
enabled, which you should. Always. Otherwise, you're using identifiers that you haven't declared and they are all implicitly declared as Variants.
You could resolve the problem with:
for line in open(your_file_path, 'rb'):
'rb' is reading the file in binary mode. Read more here.
Try these utility methods of mine:
using System.ComponentModel;
using System.Globalization;
using System.Linq;
public static T GetAttribute<T>(this MemberInfo member, bool isRequired)
where T : Attribute
{
var attribute = member.GetCustomAttributes(typeof(T), false).SingleOrDefault();
if (attribute == null && isRequired)
{
throw new ArgumentException(
string.Format(
CultureInfo.InvariantCulture,
"The {0} attribute must be defined on member {1}",
typeof(T).Name,
member.Name));
}
return (T)attribute;
}
public static string GetPropertyDisplayName<T>(Expression<Func<T, object>> propertyExpression)
{
var memberInfo = GetPropertyInformation(propertyExpression.Body);
if (memberInfo == null)
{
throw new ArgumentException(
"No property reference expression was found.",
"propertyExpression");
}
var attr = memberInfo.GetAttribute<DisplayNameAttribute>(false);
if (attr == null)
{
return memberInfo.Name;
}
return attr.DisplayName;
}
public static MemberInfo GetPropertyInformation(Expression propertyExpression)
{
Debug.Assert(propertyExpression != null, "propertyExpression != null");
MemberExpression memberExpr = propertyExpression as MemberExpression;
if (memberExpr == null)
{
UnaryExpression unaryExpr = propertyExpression as UnaryExpression;
if (unaryExpr != null && unaryExpr.NodeType == ExpressionType.Convert)
{
memberExpr = unaryExpr.Operand as MemberExpression;
}
}
if (memberExpr != null && memberExpr.Member.MemberType == MemberTypes.Property)
{
return memberExpr.Member;
}
return null;
}
Usage would be:
string displayName = ReflectionExtensions.GetPropertyDisplayName<SomeClass>(i => i.SomeProperty);
This is my code .This works for me
componentDidMount(){
axios.get('http://localhost:5000/supplier').then(
response => {
console.log(response)
this.setState({suppliers:response.data.data})
}
)
.catch(error => {
console.log(error)
})
}
componentDidUpdate(){
this.componentDidMount();
}
window.location.reload(); I think this thing is not good for react js
Temi's answer is nearly correct, but you cannot call an asynchronous function from a non asynchronous function like he is suggesting. What you need to do is make asynchronous calls in a synchronous function like so :
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IServiceProvider serviceProvider)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseIdentity();
// Add external authentication middleware below. To configure them please see https://go.microsoft.com/fwlink/?LinkID=532715
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
CreateRoles(serviceProvider);
}
private void CreateRoles(IServiceProvider serviceProvider)
{
var roleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
var userManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();
Task<IdentityResult> roleResult;
string email = "[email protected]";
//Check that there is an Administrator role and create if not
Task<bool> hasAdminRole = roleManager.RoleExistsAsync("Administrator");
hasAdminRole.Wait();
if (!hasAdminRole.Result)
{
roleResult = roleManager.CreateAsync(new IdentityRole("Administrator"));
roleResult.Wait();
}
//Check if the admin user exists and create it if not
//Add to the Administrator role
Task<ApplicationUser> testUser = userManager.FindByEmailAsync(email);
testUser.Wait();
if (testUser.Result == null)
{
ApplicationUser administrator = new ApplicationUser();
administrator.Email = email;
administrator.UserName = email;
Task<IdentityResult> newUser = userManager.CreateAsync(administrator, "_AStrongP@ssword!");
newUser.Wait();
if (newUser.Result.Succeeded)
{
Task<IdentityResult> newUserRole = userManager.AddToRoleAsync(administrator, "Administrator");
newUserRole.Wait();
}
}
}
The key to this is the use of the Task<> class and forcing the system to wait in a slightly different way in a synchronous way.
You can remove a string from an array like this:
array = ["Bob", "Same"]
array.remove("Bob")
You need to use the .toFixed()
method
It takes as a parameter the number of digits to show after the decimal point.
$(document).ready(function() {
$('.add').click(function() {
var value = parseFloat($('#total').text()) + parseFloat($(this).data('amount'))/100
$('#total').text( value.toFixed(2) );
});
})
Here is the thing, there is no way to "temporarily" disable cross-domain XMLHttpRequest, if you can disable it temporarily then it can be disabled permanently. This is a rather common problem in the modern-day of AJAX programming and is most often solved using the technique known as cross-domain scripting.
The idea here being is that if you call out to a cross-domain script it returns JavaScript (JSON) results that are then passed on to a function on your end.
Here is some sample code to illustrate how it may look from a JavaScript code perspective:
function request_some_data() {
var s = "http://my.document.url.com/my_data?p1=v1&p2=v2&callback=myfunc";
try {
try{
document.write("<scr"+"ipt type='text/javascript' src='"+s+"'></scr"+"ipt>");
}
catch(e){
var x = document.createElement("script");
x.src = s;
document.getElementsByTagName("head")[0].appendChild(x);
}
}
catch (e) {
alert(e.message);
}
}
You will then define a function in your code that receives the data and in the server you "handle" the callback case, here is the client-side JavaScript:
function myfunc(data) {
alert(data);
}
And on the server side, here i'm giving a PHP example but this can be done just as easily in Java or what-ever your server-side technology is:
<?php
if($_GET["callback"]) {
print($_GET["callback"] . "(");
}
/* place your JSON object code/logic here */
if($_GET["callback"]) {
print(");");
}
?>
Note that what you are generating on the server side winds up being some JavaScript that gets executed on the client side.
Try this one, with code coloration:
list[:10]
will give you the first 10 elements of this list using slicing.
However, note, it's best not to use list
as a variable identifier as it's already used by Python: list()
To find out more about these type of operations you might find this tutorial on lists helpful and the link @DarenThomas provided Explain Python's slice notation - thanks Daren)
Many answers already, but one more option
PyPSExec https://pypi.org/project/pypsexec/
It's a python clone of the famous psexec. Works without any installation on the remote windows machine.
You're thinking too complicated. It's actually just $('#'+openaddress)
.
Yes, You can use gcc to compile your asm code. Use -c for compilation like this:
gcc -c file.S -o file.o
This will give object code file named file.o. To invoke linker perform following after above command:
gcc file.o -o file
The struct module mimics C structures. It takes more CPU cycles for a processor to read a 16-bit word on an odd address or a 32-bit dword on an address not divisible by 4, so structures add "pad bytes" to make structure members fall on natural boundaries. Consider:
struct { 11
char a; 012345678901
short b; ------------
char c; axbbcxxxdddd
int d;
};
This structure will occupy 12 bytes of memory (x being pad bytes).
Python works similarly (see the struct documentation):
>>> import struct
>>> struct.pack('BHBL',1,2,3,4)
'\x01\x00\x02\x00\x03\x00\x00\x00\x04\x00\x00\x00'
>>> struct.calcsize('BHBL')
12
Compilers usually have a way of eliminating padding. In Python, any of =<>! will eliminate padding:
>>> struct.calcsize('=BHBL')
8
>>> struct.pack('=BHBL',1,2,3,4)
'\x01\x02\x00\x03\x04\x00\x00\x00'
Beware of letting struct handle padding. In C, these structures:
struct A { struct B {
short a; int a;
char b; char b;
}; };
are typically 4 and 8 bytes, respectively. The padding occurs at the end of the structure in case the structures are used in an array. This keeps the 'a' members aligned on correct boundaries for structures later in the array. Python's struct module does not pad at the end:
>>> struct.pack('LB',1,2)
'\x01\x00\x00\x00\x02'
>>> struct.pack('LBLB',1,2,3,4)
'\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x04'
If its ubuntu then go ahead with this, already tested.:--
first, installing dependencies
sudo aptitude install openssl build-essential xorg libssl-dev
for 64bits OS
wget http://wkhtmltopdf.googlecode.com/files/wkhtmltopdf-0.9.9-static-amd64.tar.bz2
tar xvjf wkhtmltopdf-0.9.9-static-amd64.tar.bz2
mv wkhtmltopdf-amd64 /usr/local/bin/wkhtmltopdf
chmod +x /usr/local/bin/wkhtmltopdf
for 32bits OS
wget http://wkhtmltopdf.googlecode.com/files/wkhtmltopdf-0.9.9-static-i386.tar.bz2
tar xvjf wkhtmltopdf-0.9.9-static-i386.tar.bz2
mv wkhtmltopdf-i386 /usr/local/bin/wkhtmltopdf
chmod +x /usr/local/bin/wkhtmltopdf
I believe commenting out display_errors in php.ini won't work because the default is On. You must set it to 'Off' instead.
Don't forget to restart Apache to apply configuration changes.
Also note that while you can set display_errors at runtime, changing it here does not affect FATAL errors.
As noted by others, ideally during development you should run with error_reporting at the highest level possible and display_errors enabled. While annoying when you first start out, these errors, warnings, notices and strict coding advice all add up and enable you to becoem a better coder.
Reverting the revert will do the trick
For example,
If abcdef
is your commit and ghijkl
is the commit you have when you reverted the commit abcdef
, then run:
git revert ghijkl
This will revert the revert
there are some mistakes in your code - the first: you havn't closed you p
-tag:
<a href="http//www.google.com"><p style="text-align:center">Search</p></a>
next: p
stands for 'paragraph' and is a block-element (so it's causing a line-break). what you wanted to use there is a span
, wich is just an inline-element for formatting:
<a href="http//www.google.com"><span style="text-align:center">Search</span></a>
but if you just want to add a style to your link, why don't you set the style for that link directly:
<a href="http//www.google.com" style="text-align:center">Search</a>
in the end, this would at least be correct html, but still not exactly what you want, because text-align:center
centers the text in that element, so you would have to set that for the element that contains this links (this piece of html isn't posted, so i can't correct you, but i hope you understand) - to show this, i'll use a simple div
:
<div style="text-align:center">
<a href="http//www.google.com">Search</a>
<!-- more links here -->
</div>
EDIT: some more additions to your question:
p
is not a 'function', but you're right, this is causing the problem (because it's a block-element)In Eztrieve it's really easy, below is an example how you could code it:
//STEP01 EXEC PGM=EZTPA00
//FILEA DD DSN=FILEA,DISP=SHR
//FILEB DD DSN=FILEB,DISP=SHR
//FILEC DD DSN=FILEC.DIF,
// DISP=(NEW,CATLG,DELETE),
// SPACE=(CYL,(100,50),RLSE),
// UNIT=PRMDA,
// DCB=(RECFM=FB,LRECL=5200,BLKSIZE=0)
//SYSOUT DD SYSOUT=*
//SRTMSG DD SYSOUT=*
//SYSPRINT DD SYSOUT=*
//SYSIN DD *
FILE FILEA
FA-KEY 1 7 A
FA-REC1 8 10 A
FA-REC2 18 5 A
FILE FILEB
FB-KEY 1 7 A
FB-REC1 8 10 A
FB-REC2 18 5 A
FILE FILEC
FILE FILED
FD-KEY 1 7 A
FD-REC1 8 10 A
FD-REC2 18 5 A
JOB INPUT (FILEA KEY FA-KEY FILEB KEY FB-KEY)
IF MATCHED
FD-KEY = FB-KEY
FD-REC1 = FA-REC1
FD-REC2 = FB-REC2
PUT FILED
ELSE
IF FILEA
PUT FILEC FROM FILEA
ELSE
PUT FILEC FROM FILEB
END-IF
END-IF
/*
The Collection#filter
method really does eager load all members.
Filtering at the SQL level will be added in doctrine 2.3.
There's a simpler way by leveraging the use of bind
and call
methods.
By setting private variables to an object, you can leverage that object's scope.
function TestClass (value) {
// The private value(s)
var _private = {
value: value
};
// `bind` creates a copy of `getValue` when the object is instantiated
this.getValue = TestClass.prototype.getValue.bind(_private);
// Use `call` in another function if the prototype method will possibly change
this.getValueDynamic = function() {
return TestClass.prototype.getValue.call(_private);
};
};
TestClass.prototype.getValue = function() {
return this.value;
};
This method isn't without drawbacks. Since the scope context is effectively being overridden, you don't have access outside of the _private
object. However, it isn't impossible though to still give access to the instance object's scope. You can pass in the object's context (this
) as the second argument to bind
or call
to still have access to it's public values in the prototype function.
function TestClass (value) {
var _private = {
value: value
};
this.message = "Hello, ";
this.getMessage = TestClass.prototype.getMessage.bind(_private, this);
}
TestClass.prototype.getMessage = function(_public) {
// Can still access passed in arguments
// e.g. – test.getValues('foo'), 'foo' is the 2nd argument to the method
console.log([].slice.call(arguments, 1));
return _public.message + this.value;
};
var test = new TestClass("World");
test.getMessage(1, 2, 3); // [1, 2, 3] (console.log)
// => "Hello, World" (return value)
test.message = "Greetings, ";
test.getMessage(); // [] (console.log)
// => "Greetings, World" (return value)
This is concerning "Build Solution" option only.
I got totally fed up with Visual Studio's inability to really clean solutions and wrote this little tool that will do it for you.
Close your solution in VS first and drag its folder from Windows Explorer into this app or into its icon. Depending on the setting at the bottom of its window, it can also remove additional stuff, that will help if you try to manually upload your solution to GitHub or share it with someone else:
In a nutshell, it will place all "Debug" folders, Intellisense, and other caches that can be rebuilt by VS into Recycle Bin for you.
In ES2015/ES6 you can use "*".repeat(n)
So just add this to your projects, and your are good to go.
String.prototype.repeat = String.prototype.repeat ||
function(n) {
if (n < 0) throw new RangeError("invalid count value");
if (n == 0) return "";
return new Array(n + 1).join(this.toString())
};
Technically, there are two issues with the code posted by BGM:
the adding of the handlers in the WaitForPageLoad method is potentially too late. The navigation is initiated before the handlers are added which means that in very rare cases where the browser already has the page it may complete before the handlers are added in which case you will miss the event and sit forever waiting.
The solution is to add the handlers before the navigation starts and remove them after the navigation completed
This means the WaitForPageLoad method needs to be split into two methods. One is called before initiating the navigation. It should set the handlers. The second part does the ReadyState monitoring and cleans up when 'Ready'.
good programming practices is to add a timeout so that a lost (or crashed, or looping) browser doesn't make your code wait forever for the document completed even
You can also specify the columns in a select like so:
$c = Customer::select('*', DB::raw('customers.id AS id, customers.first_name AS first_name, customers.last_name AS last_name'))
->leftJoin('orders', function($join) {
$join->on('customers.id', '=', 'orders.customer_id')
})->whereNull('orders.customer_id')->first();
A string to char array is as simple as
String str = "someString";
char[] charArray = str.toCharArray();
Can you explain a little more on what you are trying to do?
* Update *
if I am understanding your new comment, you can use a byte array and example is provided.
byte[] bytes = ByteBuffer.allocate(4).putInt(1695609641).array();
for (byte b : bytes) {
System.out.format("0x%x ", b);
}
With the following output
0x65 0x10 0xf3 0x29
Well, actually, React is not suitable for calling child methods from the parent. Some frameworks, like Cycle.js, allow easily access data both from parent and child, and react to it.
Also, there is a good chance you don't really need it. Consider calling it into existing component, it is much more independent solution. But sometimes you still need it, and then you have few choices:
UPD: if you need to share some functionality which doesn't involve any state (like static functions in OOP), then there is no need to contain it inside components. Just declare it separately and invoke when need:
let counter = 0;
function handleInstantiate() {
counter++;
}
constructor(props) {
super(props);
handleInstantiate();
}
It's like copy semantics, but instead of having to duplicate all of the data you get to steal the data from the object being "moved" from.
Try this.
def subtract_lists(a, b):
""" Subtracts two lists. Throws ValueError if b contains items not in a """
# Terminate if b is empty, otherwise remove b[0] from a and recurse
return a if len(b) == 0 else [a[:i] + subtract_lists(a[i+1:], b[1:])
for i in [a.index(b[0])]][0]
>>> x = [1,2,3,4,5,6,7,8,9,0]
>>> y = [1,3,5,7,9]
>>> subtract_lists(x,y)
[2, 4, 6, 8, 0]
>>> x = [1,2,3,4,5,6,7,8,9,0,9]
>>> subtract_lists(x,y)
[2, 4, 6, 8, 0, 9] #9 is only deleted once
>>>
Right-click on toolbar then click on "choose item" in context menu. A dialog with registered components pops up. in this dialog click "Browse" to select your assembly with the usercontrol you want to use.
PS. This assembly should be registered before.
$.ajax({
url: '//freegeoip.net/json/',
type: 'POST',
dataType: 'jsonp',
success: function(location) {
alert(location.ip);
}
});
This code will work https sites too
to take output in MySQL you can use if statement SYNTAX:
if(condition,if_true,if_false)
the if_true and if_false can be used to verify and to show output as there is no print statement in the MySQL
The shortcut is: CTRL+_
Have a look here http://ubuntuforums.org/showthread.php?t=1005737
There are 3 steps that needs to be run.
It is very interesting that this simplest usage is not clearly described anywhere. And i believe there is a danger, you should pay attention to the verified_email
parameter coming in the response. Because if I am not wrong it may yield fake emails to register your application. (This is just my interpretation, has a fair chance that I may be wrong!)
I find facebook's OAuth mechanics much much clearly described.
I used string.js's latinise() method, which lets you do it like this:
var output = S(input).latinise().toString();
You simply need to specify your current RE, followed by a letter/number followed by your current RE again:
^[A-Z0-9 _]*[A-Z0-9][A-Z0-9 _]*$
Since you've now stated they're Javascript REs, there's a useful site here where you can test the RE against input data.
If you want lowercase letters as well:
^[A-Za-z0-9 _]*[A-Za-z0-9][A-Za-z0-9 _]*$
In Linux Kernel, present pages are physical pages of RAM which kernel can see. Literally, present pages is total size of RAM in 4KB unit.
grep present /proc/zoneinfo | awk '{sum+=$2}END{print sum*4,"KB"}'
The 'MemTotal' form /proc/meminfo is the total size of memory managed by buddy system.And we can also compute it like this:
grep managed /proc/zoneinfo | awk '{sum+=$2}END{print sum*4,"KB"}'
I also spent several hours fighting with this as well. The fix is real simple. Edit your Entitlements.plist file in the root of your project's directory. Find the line that says <key>get-task-allow</key>
. Underneath it should be <false/>
. Change that to <true/>
.
Bootstrap Tokenfield seems good too: http://sliptree.github.io/bootstrap-tokenfield/
Building on modle13's answer, but without the re
module dependency.
def iter_find(haystack, needle):
return [i for i in range(0, len(haystack)) if haystack[i:].startswith(needle)]
I kinda wish this was a builtin string method.
>>> iter_find("http://stackoverflow.com/questions/1883980/", '/')
[5, 6, 24, 34, 42]
Yeah, I missed ++ and -- functionality as well. A few million lines of c code engrained that kind of thinking in my old head, and rather than fight it... Here's a class I cobbled up that implements:
pre- and post-increment, pre- and post-decrement, addition,
subtraction, multiplication, division, results assignable
as integer, printable, settable.
Here 'tis:
class counter(object):
def __init__(self,v=0):
self.set(v)
def preinc(self):
self.v += 1
return self.v
def predec(self):
self.v -= 1
return self.v
def postinc(self):
self.v += 1
return self.v - 1
def postdec(self):
self.v -= 1
return self.v + 1
def __add__(self,addend):
return self.v + addend
def __sub__(self,subtrahend):
return self.v - subtrahend
def __mul__(self,multiplier):
return self.v * multiplier
def __div__(self,divisor):
return self.v / divisor
def __getitem__(self):
return self.v
def __str__(self):
return str(self.v)
def set(self,v):
if type(v) != int:
v = 0
self.v = v
You might use it like this:
c = counter() # defaults to zero
for listItem in myList: # imaginary task
doSomething(c.postinc(),listItem) # passes c, but becomes c+1
...already having c, you could do this...
c.set(11)
while c.predec() > 0:
print c
....or just...
d = counter(11)
while d.predec() > 0:
print d
...and for (re-)assignment into integer...
c = counter(100)
d = c + 223 # assignment as integer
c = c + 223 # re-assignment as integer
print type(c),c # <type 'int'> 323
...while this will maintain c as type counter:
c = counter(100)
c.set(c + 223)
print type(c),c # <class '__main__.counter'> 323
EDIT:
And then there's this bit of unexpected (and thoroughly unwanted) behavior,
c = counter(42)
s = '%s: %d' % ('Expecting 42',c) # but getting non-numeric exception
print s
...because inside that tuple, getitem() isn't what used, instead a reference to the object is passed to the formatting function. Sigh. So:
c = counter(42)
s = '%s: %d' % ('Expecting 42',c.v) # and getting 42.
print s
...or, more verbosely, and explicitly what we actually wanted to happen, although counter-indicated in actual form by the verbosity (use c.v
instead)...
c = counter(42)
s = '%s: %d' % ('Expecting 42',c.__getitem__()) # and getting 42.
print s
Use javax.servlet.http.HttpServletResponse class
Example:
javax.servlet.http.HttpServletResponse.SC_UNAUTHORIZED //401
javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR //500
Bydefault lazy loading is true.Lazy loading means when the select query is executed it will not hit the database. It will wait for getter function i.e when we required then ,it will fetch from the datbase. for example: You are a parent who has a kid with a lot of toys. But the current issue is whenever you call him (we assume you have a boy), he comes to you with all his toys as well. Now this is an issue since you do not want him carrying around his toys all the time. So being the rationale parent, you go right ahead and define the toys of the child as LAZY. Now whenever you call him, he just comes to you without his toys.
We can try like this
recyclerView.getLayoutManager().smoothScrollToPosition(recyclerView,new RecyclerView.State(), recyclerView.getAdapter().getItemCount());
As per the documentation you can add comments only at the time of creating table. So it is must to have table definition. One way to automate it using the script to read the definition and update your comments.
Reference:
http://cornempire.net/2010/04/15/add-comments-to-column-mysql/
You can also use the isNaN()
function:
var s = ''
var num = isNaN(parseInt(s)) ? 0 : parseInt(s)
From the GNU UPC website:
Compiler build fails with fatal error: gnu/stubs-32.h: No such file or directory
This error message shows up on the 64 bit systems where GCC/UPC multilib feature is enabled, and it indicates that 32 bit version of libc is not installed. There are two ways to correct this problem:
- Install 32 bit version of glibc (e.g. glibc-devel.i686 on Fedora, CentOS, ..)
- Disable 'multilib' build by supplying "--disable-multilib" switch on the compiler configuration command
came out of this issue by changing the version in package.json file and also changing the name of the package and finally deleted the package-lock.json file
The below code should apply different CSS classes based on your Model's CanEdit
Property value .
<div class="@(Model.CanEdit?"visible-item":"hidden-item")">Some links</div>
But if it is something important like Edit/Delete links, you shouldn't be simply hiding,because people can update the css class/HTML markup in their browser and get access to your important link. Instead you should be simply not Rendering the important stuff to the browser.
@if(Model.CanEdit)
{
<div>Edit/Delete link goes here</div>
}
In here you can save the phone number as international formatted phone number
internationalFormatPhoneNumber = phoneUtil.format(givenPhoneNumber, PhoneNumberFormat.INTERNATIONAL);
it return the phone number as International format +94 71 560 4888
so now I have get country code as this
String countryCode = internationalFormatPhoneNumber.substring(0,internationalFormatPhoneNumber.indexOf('')).replace('+', ' ').trim();
Hope this will help you
You can try this to get infos like:
git config --get user.name
git config --get user.email
There's nothing like "first name" and "last name" for the user.
Hope this will help.
Also, if you'd like to know global memory rather than node process':
var os = require('os');
os.freemem();
os.totalmem();
You must create your own class type and override the ToString() method to return the text you want. Here is a simple example of a class you can use:
public class ComboboxItem
{
public string Text { get; set; }
public object Value { get; set; }
public override string ToString()
{
return Text;
}
}
The following is a simple example of its usage:
private void Test()
{
ComboboxItem item = new ComboboxItem();
item.Text = "Item text1";
item.Value = 12;
comboBox1.Items.Add(item);
comboBox1.SelectedIndex = 0;
MessageBox.Show((comboBox1.SelectedItem as ComboboxItem).Value.ToString());
}
Here's a one-liner that removes all objects except for functions:
rm(list = setdiff(ls(), lsf.str()))
It uses setdiff
to find the subset of objects in the global environment (as returned by ls()
) that don't have mode function
(as returned by lsf.str()
)
It seems like you want to do that:
dict.keys()[-1]
dict.keys()
returns a list of your dictionary's keys. Once you got the list, the -1 index allows you getting the last element of a list.
Since a dictionary is unordered*, it's doesn't make sense to get the last key of your dictionary.
Perhaps you want to sort them before. It would look like that:
sorted(dict.keys())[-1]
Note:
In Python 3, the code is
list(dict)[-1]
This is no longer the case. Dictionary keys are officially ordered as of Python 3.7 (and unofficially in 3.6).
Don't bother checking if the file exists, just try to remove it.
rm -f /p/a/t/h
# or
rm /p/a/t/h 2> /dev/null
Note that the second command will fail (return a non-zero exit status) if the file did not exist, but the first will succeed owing to the -f
(short for --force
) option. Depending on the situation, this may be an important detail.
But more likely, if you are appending to the file it is because your script is using >>
to redirect something into the file. Just replace >>
with >
. It's hard to say since you've provided no code.
Note that you can do something like test -f /p/a/t/h && rm /p/a/t/h
, but doing so is completely pointless. It is quite possible that the test will return true but the /p/a/t/h will fail to exist before you try to remove it, or worse the test will fail and the /p/a/t/h will be created before you execute the next command which expects it to not exist. Attempting this is a classic race condition. Don't do it.
Yes, you are correct, the issue is with 64-bit Python and 32-bit installer for setuptools.
The best way to get 64-bit setuptools installed on Windows is to download ez_setup.py to C:\Python27\Scripts and run it. It will download appropriate 64-bit .egg file for setuptools and install it for you.
Source: http://pypi.python.org/pypi/setuptools
P.S. I'd recommend against using 3rd party 64-bit .exe setuptools installers or manipulating registry
Not totally related, but you can also check for both undefined
AND empty
(for e.g my_variable:
) variable. (NOTE: only works with ansible version > 1.9, see: link)
- name: Create user
user:
name: "{{ ((my_variable == None) | ternary('default_value', my_variable)) \
if my_variable is defined else 'default_value' }}"
This works even if the script is sourced:
source "$( dirname "${BASH_SOURCE[0]}" )/incl.sh"
Short answer: classmaps are static while PSR autoloading is dynamic.
If you don't want to use classmaps, use PSR autoloading instead.
.sort()
, in pymongo, takes key
and direction
as parameters.
So if you want to sort by, let's say, id
then you should .sort("_id", 1)
For multiple fields:
.sort([("field1", pymongo.ASCENDING), ("field2", pymongo.DESCENDING)])
\b(?=\w)(?!(ma|(t){1}))\b(\w*)
this is for the given regex.
the \b is to find word boundary.
the positive look ahead (?=\w) is here to avoid spaces.
the negative look ahead over the original regex is to prevent matches of it.
and finally the (\w*) is to catch all the words that are left.
the group that will hold the words is group 3.
the simple (?!pattern) will not work as any sub-string will match
the simple ^(?!(?:m{2}|t)$).*$ will not work as it's granularity is full lines
pill ${this.props.styleName}
will get "pill undefined" when you don't set the props
I prefer
className={ "pill " + ( this.props.styleName || "") }
or
className={ "pill " + ( this.props.styleName ? this.props.styleName : "") }
if your column is varchar
use annotation length
@Column(length = 255)
or use another column type
@Column(columnDefinition="TEXT")
1) JTable knows JCheckbox with built-in Boolean TableCellRenderers and TableCellEditor by default, then there is contraproductive declare something about that,
2) AbstractTableModel should be useful, where is in the JTable
required to reduce/restrict/change nested and inherits methods by default implemented in the DefaultTableModel
,
3) consider using DefaultTableModel
, (if you are not sure about how to works) instead of AbstractTableModel
,
could be generated from simple code:
import javax.swing.*;
import javax.swing.table.*;
public class TableCheckBox extends JFrame {
private static final long serialVersionUID = 1L;
private JTable table;
public TableCheckBox() {
Object[] columnNames = {"Type", "Company", "Shares", "Price", "Boolean"};
Object[][] data = {
{"Buy", "IBM", new Integer(1000), new Double(80.50), false},
{"Sell", "MicroSoft", new Integer(2000), new Double(6.25), true},
{"Sell", "Apple", new Integer(3000), new Double(7.35), true},
{"Buy", "Nortel", new Integer(4000), new Double(20.00), false}
};
DefaultTableModel model = new DefaultTableModel(data, columnNames);
table = new JTable(model) {
private static final long serialVersionUID = 1L;
/*@Override
public Class getColumnClass(int column) {
return getValueAt(0, column).getClass();
}*/
@Override
public Class getColumnClass(int column) {
switch (column) {
case 0:
return String.class;
case 1:
return String.class;
case 2:
return Integer.class;
case 3:
return Double.class;
default:
return Boolean.class;
}
}
};
table.setPreferredScrollableViewportSize(table.getPreferredSize());
JScrollPane scrollPane = new JScrollPane(table);
getContentPane().add(scrollPane);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
TableCheckBox frame = new TableCheckBox();
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.pack();
frame.setLocation(150, 150);
frame.setVisible(true);
}
});
}
}
You can get the concatenated year and week number (200945) using the YEARWEEK() function. If I understand your goal correctly, that should enable you to group your multi-year data.
If you need the actual timestamp for the start of the week, it's less nice:
DATE_SUB( field, INTERVAL DAYOFWEEK( field ) - 1 DAY )
For monthly ordering, you might consider the LAST_DAY() function - sort would be by last day of the month, but that should be equivalent to sorting by first day of the month ... shouldn't it?
The postition:absolute;
tag positions the element relative to it's immediate parent.
I noticed that even in the examples, there isn't room for scrolling, and when i tried it out, it didn't work.
Therefore, to pull off the facebook floating menu, the position:fixed;
tag should be used instead. It displaces/keeps the element at the given/specified location, and the rest of the page can scroll smoothly - even with the responsive ones.
Please see CSS postion attribute documentation when you can :)
Encountered this in Ubuntu for Windows, try running first
sudo apt-get update
sudo apt-get upgrade
then
sudo apt-get install npm
Tools >> Options >> Designers and uncheck “Prevent Saving changes that require table re-creation”:
Parsing command line arguments in a primitive way as explained in the above answers is reasonable as long as the number of parameters that you need to deal with is not too much.
I strongly suggest you to use an industrial strength library for handling the command line arguments.
This will make your code more professional.
Such a library for C++ is available in the following website. I have used this library in many of my projects, hence I can confidently say that this one of the easiest yet useful library for command line argument parsing. Besides, since it is just a template library, it is easier to import into your project. http://tclap.sourceforge.net/
A similar library is available for C as well. http://argtable.sourceforge.net/
add class="loading" in the body tag then use below script with follwing css code
body {
-webkit-transition: background-color 1s;
transition: background-color 1s;
}
html, body { min-height: 100%; }
body.loading {
background: #333 url('http://code.jquery.com/mobile/1.3.1/images/ajax-loader.gif') no-repeat 50% 50%;
-webkit-transition: background-color 0;
transition: background-color 0;
opacity: 0;
-webkit-transition: opacity 0;
transition: opacity 0;
}
Use this code
var body = document.getElementsByTagName('body')[0];
var removeLoading = function() {
setTimeout(function() {
body.className = body.className.replace(/loading/, '');
}, 3000);
};
removeLoading();
Another alternative is dotnetprojects SVGImage
This allows native use of .svg files directly in xaml.
The nice part is, it is only one assembly which is about 100k. In comparision to sharpvectors which is much bigger any many files.
Usage:
...
xmlns:svg1="clr-namespace:SVGImage.SVG;assembly=DotNetProjects.SVGImage"
...
<svg1:SVGImage Name="mySVGImage" Source="/MyDemoApp;component/Resources/MyImage.svg"/>
...
That's all.
See:
I understand you want to open a xml file using php. That's called to parse a xml file. The best reference is here.
When we make a dump file with mysqldump
, what it contains is a big SQL script for recreating the databse contents. So we restore it by using starting up MySQL’s command-line client:
mysql -uroot -p
(where root
is our admin user name for MySQL), and once connected to the database we need commands to create the database and read the file in to it:
create database new_db;
use new_db;
\. dumpfile.sql
Details will vary according to which options were used when creating the dump file.
if you have directory on your path where you want to sign with a given identifyfile you can specify to use a specific identify file via the .ssh/config file by setting the ControlPath
e.g.:
host github.com
ControlPath ~/Projects/work/**
HostName github.com
IdentityFile ~/.ssh/id_work
User git
Then ssh
will use the specified identity file when doing git commands under the given work path.
For my case, I can use like this.
td { white-space:pre-line , word-break: break-all}
How about
<img style="display: none;" src="a.gif">
That will disable the display completely, and not leave a placeholder
You are using a function for which the compiler has not seen a declaration ("prototype") yet.
For example:
int main()
{
fun(2, "21"); /* The compiler has not seen the declaration. */
return 0;
}
int fun(int x, char *p)
{
/* ... */
}
You need to declare your function before main, like this, either directly or in a header:
int fun(int x, char *p);
This code will help you to add button without any unwanted padding,
RawMaterialButton(
elevation: 0.0,
child: Icon(Icons.add),
onPressed: (){},
constraints: BoxConstraints.tightFor(
width: 56.0,
height: 56.0,
),
shape: CircleBorder(),
fillColor: Color(0xFF4C4F5E),
),
First Collection is class Interface and you can not instantiate. Collection API
List Ver APi is also an interface class.
It may be so
List list = Collections.synchronizedList(new ArrayList(...));
ver enter link description here
Collection collection= Collections.synchronizedList(new ArrayList(...));
You can edit style with pure Javascript. No library needed, supported by all browsers except IE where you need to set to ''
instead of null
(see comments).
var element = document.getElementById('sample_id');
element.style.width = null;
element.style.height = null;
For more information, you can refer to HTMLElement.style documentation on MDN.
var top = $('html').offset().top;
should do it.
edit: this is the negative of $(document).scrollTop()
var a = new Array();
a.push({"1": "apple", "2": "banana"});
a.push({"3": "coconut", "4": "mango"});
GetIndexByValue(a, "coconut");
function GetIndexByValue(arrayName, value) {
var keyName = "";
var index = -1;
for (var i = 0; i < arrayName.length; i++) {
var obj = arrayName[i];
for (var key in obj) {
if (obj[key] == value) {
keyName = key;
index = i;
}
}
}
//console.log(index);
return index;
}
I downloaded the .whl file from http://www.lfd.uci.edu/~gohlke/pythonlibs/ and then did:
pip install scipy-0.19.1-cp27-cp27m-win32.whl
Note that the version you need to use (win32/win_amd-64) depends on the version of Python and not that of Windows.
Remember to run "android update avd -n avd_name" after change in Android SDK path.
There's always the "brute force":
Search->File
Type the following in "Containing text" -> ^.*$
. Then check the "Regular Expression" checkbox
Type the following in "File name patterns" -> *.java
Click "Search"
Check the number of matches in the "Search" Tab.
Problems only surface when I am I trying to give the first loaded content an active state
Does this mean that you want to add a class to the first button?
$('.o-links').click(function(e) { // ... }).first().addClass('O_Nav_Current');
instead of using IDs for the slider's items and resetting html contents you can use classes and indexes:
CSS:
.image-area { width: 100%; height: auto; display: none; } .image-area:first-of-type { display: block; }
JavaScript:
var $slides = $('.image-area'), $btns = $('a.o-links'); $btns.on('click', function (e) { var i = $btns.removeClass('O_Nav_Current').index(this); $(this).addClass('O_Nav_Current'); $slides.filter(':visible').fadeOut(1000, function () { $slides.eq(i).fadeIn(1000); }); e.preventDefault(); }).first().addClass('O_Nav_Current');
I am using JSCH since about 2000 and still find it a good library to use. I agree it is not documented well enough but the provided examples seem good enough to understand that is required in several minutes, and user friendly Swing, while this is quite original approach, allows to test the example quickly to make sure it actually works. It is not always true that every good project needs three times more documentation than the amount of code written, and even when such is present, this not always helps to write faster a working prototype of your concept.
add an ALIAS
on the subquery,
SELECT COUNT(made_only_recharge) AS made_only_recharge
FROM
(
SELECT DISTINCT (identifiant) AS made_only_recharge
FROM cdr_data
WHERE CALLEDNUMBER = '0130'
EXCEPT
SELECT DISTINCT (identifiant) AS made_only_recharge
FROM cdr_data
WHERE CALLEDNUMBER != '0130'
) AS derivedTable -- <<== HERE
myTest.js
module.exports.get = function () {};
exports.put = function () {};
console.log(module.exports)
// output: { get: [Function], put: [Function] }
exports
and module.exports
are the same and a reference to the same object. You can add properties by both ways as per your convenience.
r := strings(byteData)
This also works to turn []byte
into io.Reader
Try this!
List<String> x = new ArrayList<String>(Arrays.asList("xyz", "abc"));
It's a good practice to declare the ArrayList
with interface List
if you don't have to invoke the specific methods.
Things that DID NOT WORK for me with an iPad 4/iOS 6:
My request containing: Cache-Control:no-cache
//asp.net's:
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache)
Adding cache: false to my jQuery ajax call
$.ajax(
{
url: postUrl,
type: "POST",
cache: false,
...
Only this did the trick:
var currentTime = new Date();
var n = currentTime.getTime();
postUrl = "http://www.example.com/test.php?nocache="+n;
$.post(postUrl, callbackFunction);
I searched for the top NodeJS html parser libraries.
Because my use cases didn't require a library with many features, I could focus on stability and performance.
By stability I mean that I want the library to be used long enough by the community in order to find bugs and that it will be still maintained and that open issues will be closed.
Its hard to understand the future of an open source library, but I did a small summary based on the top 10 libraries in openbase.
I divided into 2 groups according to the last commit (and on each group the order is according to Github starts):
Last commit is in the last 6 months:
jsdom - Last commit: 3 Months, Open issues: 331, Github stars: 14.9K
.
htmlparser2 - Last commit: 8 days, Open issues: 2, Github stars: 2.7K
.
parse5 - Last commit: 2 Months, Open issues: 21, Github stars: 2.5K
.
swagger-parser - Last commit: 2 Months, Open issues: 48, Github stars: 663
.
html-parse-stringify - Last commit: 4 Months, Open issues: 3, Github stars: 215
.
node-html-parser - Last commit: 7 days, Open issues: 15, Github stars: 205
.
Last commit is 6 months and above:
cheerio - Last commit: 1 year, Open issues: 174, Github stars: 22.9K
.
koa-bodyparser - Last commit: 6 months, Open issues: 9, Github stars: 1.1K
.
sax-js - Last commit: 3 Years, Open issues: 65, Github stars: 941
.
draftjs-to-html - Last commit: 1 Year, Open issues: 27, Github stars: 233
.
I picked Node-html-parser because it seems quiet fast and very active at this moment.
(*) Openbase adds much more information regarding each library like the number of contributors (with +3 commits), weekly downloads, Monthly commits, Version etc'.
(**) The table above is a snapshot according to the specific time and date - I would check the reference again and as a first step check the level of recent activity and then dive into the smaller details.
How about the simplest possible:
var myArray = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];_x000D_
var toRemove = ['b', 'c', 'g'];_x000D_
_x000D_
var myArray = myArray.filter((item) => !toRemove.includes(item));_x000D_
console.log(myArray)
_x000D_
I know this is old but it is still relevant. You can take advantage of reshape2::melt to change the dataframe into a more friendly structure for ggplot2.
Advantages:
Disadvantage:
For example:
jobsAFAM1 <- data.frame(
data_date = seq.Date(from = as.Date('2017-01-01'),by = 'day', length.out = 100),
Percent.Change = runif(5,1,100)
)
jobsAFAM2 <- data.frame(
data_date = seq.Date(from = as.Date('2017-01-01'),by = 'day', length.out = 100),
Percent.Change = runif(5,1,100)
)
jobsAFAM <- merge(jobsAFAM1, jobsAFAM2, by="data_date")
jobsAFAMMelted <- reshape2::melt(jobsAFAM, id.var='data_date')
ggplot(jobsAFAMMelted, aes(x=data_date, y=value, col=variable)) + geom_line()
The most common advice is wrong, you can't just rely on time()
. That's used for relative timing: ISO C++ doesn't specify that 1970-01-01T00:00Z
is time_t(0)
What's worse is that you can't easily figure it out, either. Sure, you can find the calendar date of time_t(0)
with gmtime
, but what are you going to do if that's 2000-01-01T00:00Z
? How many seconds were there between 1970-01-01T00:00Z
and 2000-01-01T00:00Z
? It's certainly no multiple of 60, due to leap seconds.
I believe this might Help:
System.out.println(Integer.toBinaryString(2 << 0));
System.out.println(Integer.toBinaryString(2 << 1));
System.out.println(Integer.toBinaryString(2 << 2));
System.out.println(Integer.toBinaryString(2 << 3));
System.out.println(Integer.toBinaryString(2 << 4));
System.out.println(Integer.toBinaryString(2 << 5));
Result
10
100
1000
10000
100000
1000000
Edited:
In order to get the value
of any input field, you should always use $element.val()
because jQuery
handles to retrieve the correct value based on the browser of the element type.
You don't have JSON. You have a JavaScript data structure consisting of objects, an array, some strings and some numbers.
Use JSON.stringify(object)
to turn it into (a string of) JSON text.
This function works for CRC-16 Modbus version. Not for CRC-16
You can check the content's height by setting to 1px
and then reading the scrollHeight
property:
function textAreaAdjust(element) {
element.style.height = "1px";
element.style.height = (25+element.scrollHeight)+"px";
}
_x000D_
<textarea onkeyup="textAreaAdjust(this)" style="overflow:hidden"></textarea>
_x000D_
It works under Firefox 3, IE 7, Safari, Opera and Chrome.
I don't know which version of Jquery you are using, but this works for me in jquery 1.3:
$.ajax({
type: 'POST',
url: your url,
data: $('#'+form_id).serialize(),
success: function(data) {
$('#debug').html(data);
}
});
Then you can access POST array keys as you would normally do in php.
Just try with a print_r()
.
I think you're wrapping serialized form value in an object's property, which is useless as far as i know.
Hope this helps!
keytool
comes with the JDK installation (in the bin
folder):
keytool -importcert -file "your.cer" -keystore your.jks -alias "<anything>"
This will create a new keystore and add just your certificate to it.
So, you can't convert a certificate to a keystore: you add a certificate to a keystore.
My solution is much simpler and more direct. At least it works that way on my PC (with the following specs):
me@home: my.folder$ uname -a
Linux home 3.2.0-54-generic-pae #82-Ubuntu SMP Tue Sep 10 20:29:22 UTC 2013 i686 i686 i386 GNU/Linux
with
me@home: my.folder$ convert --version
Version: ImageMagick 6.6.9-7 2012-08-17 Q16 http://www.imagemagick.org
Copyright: Copyright (C) 1999-2011 ImageMagick Studio LLC
Features: OpenMP
So, here's what I run on my file.pdf
:
me@home: my.folder$ convert -density 300 -quality 100 file.pdf file.png
for 1D and 2D arrays you can use np.savetxt to print using a specific format string:
>>> import sys
>>> x = numpy.arange(20).reshape((4,5))
>>> numpy.savetxt(sys.stdout, x, '%5.2f')
0.00 1.00 2.00 3.00 4.00
5.00 6.00 7.00 8.00 9.00
10.00 11.00 12.00 13.00 14.00
15.00 16.00 17.00 18.00 19.00
Your options with numpy.set_printoptions or numpy.array2string in v1.3 are pretty clunky and limited (for example no way to suppress scientific notation for large numbers). It looks like this will change with future versions, with numpy.set_printoptions(formatter=..) and numpy.array2string(style=..).
Something like this should work: /([^/]*)$
What language are you using? End-of-string regex signifiers can vary in different languages.
This will give a list of selected
List<ListItem> items = checkboxlist.Items.Cast<ListItem>().Where(n => n.Selected).ToList();
This will give a list of the selected boxes' values (change Value for Text if that is wanted):
var values = checkboxlist.Items.Cast<ListItem>().Where(n => n.Selected).Select(n => n.Value ).ToList()
This example will help you:
<form>
<input type="button" value="Open Window" onclick="window.open('http://www.google.com')">
</form>
You can open next page on same page by:
<input type="button" value="Open Window" onclick="window.open('http://www.google.com','_self')">
By using Constructor Injection, you assert the requirement for the dependency in a container-agnostic manner
We need the assurance from the IoC container that, before using any bean, the injection of necessary beans must be done.
In setter injection strategy, we trust the IoC container that it will first create the bean first but will do the injection right before using the bean using the setter methods. And the injection is done according to your configuration. If you somehow misses to specify any beans to inject in the configuration, the injection will not be done for those beans and your dependent bean will not function accordingly when it will be in use!
But in constructor injection strategy, container imposes (or must impose) to provide the dependencies properly while constructing the bean. This was addressed as " container-agnostic manner", as we are required to provide dependencies while creating the bean, thus making the visibility of dependency, independent of any IoC container.
Edit:
Q1: And how to prevent container from creating bean by constructor with null
values instead of missing beans?
You have no option to really miss any <constructor-arg>
(in case of Spring), because you are imposed by IoC container to provide all the constructor arguments needed to match a provided constructor for creating the bean. If you provide null
in your <constructor-arg>
intentionally. Then there is nothing IoC container can do or need to do with it!
Unfortunately, this is something you will have to ask you provider to do.
If your the owner of the server and can login to WHM it's under:
Tweak Settings => PHP Settings => Maximum Upload Size
Newer version have it listed under:
Home => Service Configuration => PHP Configuration Editor => Tweak Settings => PHP
If you're dealing with multiple values and multiple inputs you could also set up an apply function like this. In this case filtering a dataframe for GPS locations that fall withing certain ranges.
def filter_values(lat,lon):
if abs(lat - 33.77) < .01 and abs(lon - -118.16) < .01:
return True
elif abs(lat - 37.79) < .01 and abs(lon - -122.39) < .01:
return True
else:
return False
df = df[df.apply(lambda x: filter_values(x['lat'],x['lon']),axis=1)]
go to config/environments/test.rb
Rails.application.routes.default_url_options[:host] = 'localhost:3000'
You should use PDO Prepare
From the link:
Calling PDO::prepare() and PDOStatement::execute() for statements that will be issued multiple times with different parameter values optimizes the performance of your application by allowing the driver to negotiate client and/or server side caching of the query plan and meta information, and helps to prevent SQL injection attacks by eliminating the need to manually quote the parameters.
Use
python python_script.py filename
and in your Python script
import sys
print sys.argv[1]
Try using the net use
command in your script to map the share first, because you can provide it credentials. Then, your copy command should use those credentials.
net use \\<network-location>\<some-share> password /USER:username
Don't leave a trailing \ at the end of the
You can use this http://jsfiddle.net/Victornpb/S8g4E/783/
#container {
display: table;
width: 400px;
height: 400px;
}
#container > div{
display: table-row;
height: 0;
}
#container > div.fill{
height: auto;
}
Just apply the class .fill
to any of the children to make then occupy the remaining height.
<div id="container">
<div>
Lorem ipsum
</div>
<div>
Lorem ipsum
</div>
<div class="fill"> <!-- this will fill the remaining height-->
Lorem ipsum
</div>
</div>
It works with how many children you want, no additional markup is required.
This solution uses jQuery. If you want to use same placeholder text for all text inputs, you can use
$('input:text').attr('placeholder','Some New Text');
And if you want different placeholders, you can use the element's id to change placeholder
$('#element1_id').attr('placeholder','Some New Text 1');
$('#element2_id').attr('placeholder','Some New Text 2');
I'm assuming that you're wanting to insert a style
tag versus a link
tag (referencing an external CSS), so that's what the following example does:
<html>
<head>
<title>Example Page</title>
</head>
<body>
<span>
This is styled dynamically via JavaScript.
</span>
</body>
<script type="text/javascript">
var styleNode = document.createElement('style');
styleNode.type = "text/css";
// browser detection (based on prototype.js)
if(!!(window.attachEvent && !window.opera)) {
styleNode.styleSheet.cssText = 'span { color: rgb(255, 0, 0); }';
} else {
var styleText = document.createTextNode('span { color: rgb(255, 0, 0); } ');
styleNode.appendChild(styleText);
}
document.getElementsByTagName('head')[0].appendChild(styleNode);
</script>
</html>
Also, I noticed in your question that you are using innerHTML
. This is actually a non-standard way of inserting data into a page. The best practice is to create a text node and append it to another element node.
With respect to your final question, you're going to hear some people say that your work should work across all of the browsers. It all depends on your audience. If no one in your audience is using Chrome, then don't sweat it; however, if you're looking to reach the biggest audience possible, then it's best to support all major A-grade browsers
we can use different types of system fonts like below
myButton.titleLabel?.font = UIFont.boldSystemFont(ofSize: 17)
myButton.titleLabel?.font = UIFont.italicSystemFont(ofSize:UIFont.smallSystemFontSize)
myButton.titleLabel?.font = UIFont.boldSystemFont(ofSize: UIFont.buttonFontSize)
and your custom font like below
myButton.titleLabel?.font = UIFont(name: "Helvetica", size:12)
For me it wasn't working even with hibernate.hbm2ddl.auto
set to update
. It turned out that the generated creation SQL was invalid, because one of my column names (user
) was an SQL keyword. This failed softly, and it wasn't obvious what was going on until I inspected the logs.
Check out XmlTextReader class for instance.
echo $STRING | cut -d " " -f $N
The most obvious to me would be:
np.any(my_array[:, 0] == value)
Use the basename
command:
basename /home/user/new/*.txt
func Ternary(statement bool, a, b interface{}) interface{} {
if statement {
return a
}
return b
}
func Abs(n int) int {
return Ternary(n >= 0, n, -n).(int)
}
This will not outperform if/else and requires cast but works. FYI:
BenchmarkAbsTernary-8 100000000 18.8 ns/op
BenchmarkAbsIfElse-8 2000000000 0.27 ns/op
#change-avatar-file
is a file input
#change-avatar-file
is a img tag (the target of jcrop)
The "key" is FR.onloadend Event
https://developer.mozilla.org/en-US/docs/Web/API/FileReader
$('#change-avatar-file').change(function(){
var currentImg;
if ( this.files && this.files[0] ) {
var FR= new FileReader();
FR.onload = function(e) {
$('#avatar-change-img').attr( "src", e.target.result );
currentImg = e.target.result;
};
FR.readAsDataURL( this.files[0] );
FR.onloadend = function(e){
//console.log( $('#avatar-change-img').attr( "src"));
var jcrop_api;
$('#avatar-change-img').Jcrop({
bgFade: true,
bgOpacity: .2,
setSelect: [ 60, 70, 540, 330 ]
},function(){
jcrop_api = this;
});
}
}
});
To avoid confusion, paraphrasing both question and answer. I am assuming that user who posted this question wanted to save dictionary type object in JSON file format but when the user used json.dump
, this method dumped all its content in one line. Instead, he wanted to record each dictionary entry on a new line. To achieve this use:
with g as outfile:
json.dump(hostDict, outfile,indent=2)
Using indent = 2
helped me to dump each dictionary entry on a new line. Thank you @agf. Rewriting this answer to avoid confusion.
To extend a little bit answer of Calimo I present few more things you may find useful while creating this quasi dictionaries in R:
a) how to return all the VALUES of the dictionary:
>as.numeric(foo)
[1] 12 22 33
b) check whether dictionary CONTAINS KEY:
>'tic' %in% names(foo)
[1] TRUE
c) how to ADD NEW key, value pair to dictionary:
c(foo,tic2=44)
results:
tic tac toe tic2
12 22 33 44
d) how to fulfill the requirement of REAL DICTIONARY - that keys CANNOT repeat(UNIQUE KEYS)? You need to combine b) and c) and build function which validates whether there is such key, and do what you want: e.g don't allow insertion, update value if the new differs from the old one, or rebuild somehow key(e.g adds some number to it so it is unique)
e) how to DELETE pair BY KEY from dictionary:
foo<-foo[which(foo!=foo[["tac"]])]
If you already have it as a DateTime
, use:
string x = dt.ToString("yyyy-MM-dd");
See the MSDN documentation for more details. You can specify CultureInfo.InvariantCulture
to enforce the use of Western digits etc. This is more important if you're using MMM for the month name and similar things, but it wouldn't be a bad idea to make it explicit:
string x = dt.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
If you have a string to start with, you'll need to parse it and then reformat... of course, that means you need to know the format of the original string.
I want to clear here that preg_split();
is far away from it but explode();
can be used in similar way as split();
following is the comparison between split();
and explode();
usage
<?php
$date = "04/30/1973";
list($month, $day, $year) = split('[/.-]', $date);
echo $month; // foo
echo $day; // *
echo $year;
?>
URL: http://php.net/manual/en/function.split.php
<?php
$data = "04/30/1973";
list($month, $day, $year) = explode("/", $data);
echo $month; // foo
echo $day; // *
echo $year;
?>
URL: http://php.net/manual/en/function.explode.php
Here is how we can use it :)
You can build an CustButton with TouchableWithoutFeedback
, and set the effect and logic you want with onPressIn
, onPressout
or other props.
I did not see any reference to Raphael.js. So I thought I'd include it here. Raphael.js is backwards compatible all the way back to IE5 and a very early Firefox as well as all of the rest of the browsers. It uses SVG when it can and VML when it can not. What you do with it is to draw onto a canvas. Some browsers will even let you select the text that is generated. Raphael.js can be found here:
It can be as simple as creating your paper drawing area, specifying the font, font-weight, size, etc... and then telling it to put your string of text onto the paper. I am not sure if it gets around the licensing issues or not but it is drawing the text so I'm fairly certain it does circumvent the licensing issues. But check with your lawyer to be sure. :-)
From the Java tutorial, you need to create a new font and register it in the graphics environment:
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
ge.registerFont(Font.createFont(Font.TRUETYPE_FONT, new File("A.ttf")));
After this step is done, the font is available in calls to getAvailableFontFamilyNames()
and can be used in font constructors.
You are binding you click on the wrong element, you should bind it to the a
.
You are prevent default event to occur on the li
, but li
have no default behavior, a
does.
Try this:
$(document).ready(function () {
$('.nav li a').click(function(e) {
$('.nav li.active').removeClass('active');
var $parent = $(this).parent();
$parent.addClass('active');
e.preventDefault();
});
});
It seems that since XCode 7.x a lot of warnings are coming out when enabling clang module with CLANG_ENABLE_MODULES
Take a look at Lots of warnings when building with Xcode 7 with 3rd party libraries
Right clicking a specific folder can help ease your pain than just by typing the whole directory. Right click + clicking s or Right click and then click "GIT bash here"
Hope this seems helpful
It affects the whole child divs when you use the opacity feature with positions other than absolute. So another way to achieve it not to put divs inside each other and then use the position absolute for the divs. Dont use any background color for the upper div.
Normally you can set up a git repo by just using the init
command
git init
In your case, there is already a repo on a remote available. Dependent on how you access your remote repo ( with username inside the url or a ssh key which handles verification ) use just the clone
command:
git clone git@[my.url.com]:[git-repo-name].git
There are also other ways to clone the repo. This way you call it if you have a ssh key setup on your machine which verifies on pulling your repository. There are other combinations of the url if you want to include your password and username inside to login into your remote repository.
None of the other answers worked for me. Even after fixing my build path issues, doing a refresh, clean, rebuild, and restart (of both eclipse and the computer), I was still getting the little red exclamation point.
I fixed it by closing the project (right-click, close project) and reopening it (double-click the closed project), which seemed to force eclipse to "notice" that the build path problems had been corrected.
Copy the global variable to a variable in the scope in your controller.
function MyCtrl($scope) {
$scope.variable1 = variable1;
}
Then you can just access it like you tried. But note that this variable will not change when you change the global variable. If you need that, you could instead use a global object and "copy" that. As it will be "copied" by reference, it will be the same object and thus changes will be applied (but remember that doing stuff outside of AngularJS will require you to do $scope.$apply anway).
But maybe it would be worthwhile if you would describe what you actually try to achieve. Because using a global variable like this is almost never a good idea and there is probably a better way to get to your intended result.
Got this from Bing. Seems Microsoft has removed some features from the core framework and added it to a separate optional(?) framework component.
To quote from MSDN (http://msdn.microsoft.com/en-us/library/cc656912.aspx)
The .NET Framework 4 Client Profile does not include the following features. You must install the .NET Framework 4 to use these features in your application:
* ASP.NET * Advanced Windows Communication Foundation (WCF) functionality * .NET Framework Data Provider for Oracle * MSBuild for compiling
Using Java 1.8 you can use Optional
public class Main {
public static void main(String[] args) {
//example call, the methods are just dumb templates, note they are static
FutureMeal meal = getChicken().orElse(getFreeRangeChicken());
//another possible way to call this having static methods is
FutureMeal meal = getChicken().orElseGet(Main::getFreeRangeChicken); //method reference
//or if you would use a Instance of Main and call getChicken and getFreeRangeChicken
// as nonstatic methods (assume static would be replaced with public for this)
Main m = new Main();
FutureMeal meal = m.getChicken().orElseGet(m::getFreeRangeChicken); //method reference
//or
FutureMeal meal = m.getChicken().orElse(m.getFreeRangeChicken()); //method call
}
static Optional<FutureMeal> getChicken(){
//instead of returning null, you would return Optional.empty()
//here I just return it to demonstrate
return Optional.empty();
//if you would return a valid object the following comment would be the code
//FutureMeal ret = new FutureMeal(); //your return object
//return Optional.of(ret);
}
static FutureMeal getFreeRangeChicken(){
return new FutureMeal();
}
}
You would implement a logic for getChicken
to return either Optional.empty()
instead of null, or Optional.of(myReturnObject)
, where myReturnObject
is your chicken
.
Then you can call getChicken()
and if it would return Optional.empty()
the orElse(fallback)
would give you whatever the fallback would be, in your case the second method.
You need to use a directed graph instead of a graph, i.e.
G = nx.DiGraph()
Then, create a list of the edge colors you want to use and pass those to nx.draw
(as shown by @Marius).
Putting this all together, I get the image below. Still not quite the other picture you show (I don't know where your edge weights are coming from), but much closer! If you want more control of how your output graph looks (e.g. get arrowheads that look like arrows), I'd check out NetworkX with Graphviz.
You can make a workaround but this will remove the fade from all the page. The modal will popup like Facebook popups. After opening the modal try:
$('.modal-backdrop').removeClass('modal-backdrop');
Try what worked for me cool!
Create a variable private static int displayedposition = 0;
Now for the position of your RecyclerView in your Activity.
myRecyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
}
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
LinearLayoutManager llm = (LinearLayoutManager) myRecyclerView.getLayoutManager();
displayedposition = llm.findFirstVisibleItemPosition();
}
});
Place this statement where you want it to place the former site displayed in your view .
LinearLayoutManager llm = (LinearLayoutManager) mRecyclerView.getLayoutManager();
llm.scrollToPositionWithOffset(displayedposition , youList.size());
Well that's it , it worked fine for me \o/
You can use the time()
method of datetime
objects to get the time of day, which you can use for comparison without taking the date into account:
>>> this_morning = datetime.datetime(2009, 12, 2, 9, 30)
>>> last_night = datetime.datetime(2009, 12, 1, 20, 0)
>>> this_morning.time() < last_night.time()
True
Copied from my answer here: https://stackoverflow.com/a/9368199/485088
Run
ldconfig
as root to update the cache - if that still doesn't help, you need to add the path to the fileld.so.conf
(just type it in on its own line) or better yet, add the entry to a new file (easier to delete) in directoryld.so.conf.d
.
Since for some reason white isn't available for selection, I have found that mat-palette($mat-grey, 50)
was close enough to white, for my needs at least.
Explanation: Use unix command find
with -ctime
(creation time) flag
The find utility recursively descends the directory tree for each path listed, evaluating an expression (composed of the 'primaries' and 'operands') in terms of each file in the tree.
Solution: According to documenation
-ctime n[smhdw]
If no units are specified, this primary evaluates to true if the difference
between the time of last change of file status information and the time find
was started, rounded up to the next full 24-hour period, is n 24-hour peri-
ods.
If units are specified, this primary evaluates to true if the difference
between the time of last change of file status information and the time find
was started is exactly n units. Please refer to the -atime primary descrip-
tion for information on supported time units.
Formula: find <path> -ctime +[number][timeMeasurement] -ctime -[number][timeMeasurment]
Examples:
1.Find everything that were created after 1 week ago ago and before 2 weeks ago
find / -ctime +1w -ctime -2w
2.Find all javascript files (.js
) in current directory that were created between 1 day ago to 3 days ago
find . -name "*\.js" -type f -ctime +1d -ctime -3d
use the following file prefix, this will add to your perl script eTRUE and eFALSE, it will actually be REAL(!) true and false (just like java)
#!/usr/bin/perl
use strict;
use warnings;
use constant { #real true false, compatible with encode_json decode_json for later (we don't want field:false... will be field:0...)
eTRUE => bless( do{\(my $o = 1)}, 'JSON::PP::Boolean' ),
eFALSE => bless( do{\(my $o = 0)}, 'JSON::PP::Boolean' )
};
There are, actually, few reasons why you should use that.
My reason is that working with JSON, I've got 0 and 1 as values to keys, but this hack will make sure correct values are kept along your script.
A "JSON object" is actually an oxymoron. JSON is a text format describing an object, not an actual object, so data can either be in the form of JSON, or deserialised into an object.
The JSON for that would look like this:
{"KEY1":{"NAME":"XXXXXX","VALUE":100},"KEY2":{"NAME":"YYYYYYY","VALUE":200},"KEY3":{"NAME":"ZZZZZZZ","VALUE":500}}
Once you have parsed the JSON into a Javascript object (called data
in the code below), you can for example access the object for KEY2
and it's properties like this:
var obj = data.KEY2;
alert(obj.NAME);
alert(obj.VALUE);
If you have the key as a string, you can use index notation:
var key = 'KEY3';
var obj = data[key];
The identity
section goes under the system.web
section, not under authentication
:
<system.web>
<authentication mode="Windows"/>
<identity impersonate="true" userName="foo" password="bar"/>
</system.web>
mysql> INSERT INTO tb1 VALUES(1,1),(2,2),(3,3),(6,60),(7,70),(8,80);
mysql> INSERT INTO tb2 VALUES(1,1),(2,2),(3,3),(4,40),(5,50),(9,90);
DELETE records FROM one table :
mysql> DELETE tb1 FROM tb1,tb2 WHERE tb1.id= tb2.id;
DELETE RECORDS FROM both tables:
mysql> DELETE tb2,tb1 FROM tb2 JOIN tb1 USING(id);
Have you seen this already? The cause seems to be a very old libpam on one of the sides, probably on that customer.
Or the links for the version might be missing : http://www.linux.org/docs/ldp/howto/Program-Library-HOWTO/shared-libraries.html
All these answers seem a bit heavy to me.
If you just flat out remove the '\n' and move everything else back a spot, you are liable to have some characters slammed together in a weird-looking way. So why not just do the simple (and most efficient) thing: Replace all '\n's with spaces?
for (int i = 0; i < str.length();i++) {
if (str[i] == '\n') {
str[i] = ' ';
}
}
There may be ways to improve the speed of this at the edges, but it will be way quicker than moving whole chunks of the string around in memory.
You could move the conditional to:
v = [22, 13, 45, 50, 98, 69, 43, 44, 1]
[ (x+1 if x >=45 else x+5) for x in v ]
But it's starting to look a little ugly, so you might be better off using a normal loop. Note that I used v
instead of l
for the list variable to reduce confusion with the number 1 (I think l
and O
should be avoided as variable names under any circumstances, even in quick-and-dirty example code).
Adding to the answer given by @insomniac. You can create a Map
to put the parameter for RequestBody
including image.
Code for Interface
public interface ApiInterface {
@Multipart
@POST("/api/Accounts/editaccount")
Call<User> editUser (@Header("Authorization") String authorization, @PartMap Map<String, RequestBody> map);
}
Code for Java class
File file = new File(imageUri.getPath());
RequestBody fbody = RequestBody.create(MediaType.parse("image/*"), file);
RequestBody name = RequestBody.create(MediaType.parse("text/plain"), firstNameField.getText().toString());
RequestBody id = RequestBody.create(MediaType.parse("text/plain"), AZUtils.getUserId(this));
Map<String, RequestBody> map = new HashMap<>();
map.put("file\"; filename=\"pp.png\" ", fbody);
map.put("FirstName", name);
map.put("Id", id);
Call<User> call = client.editUser(AZUtils.getToken(this), map);
call.enqueue(new Callback<User>() {
@Override
public void onResponse(retrofit.Response<User> response, Retrofit retrofit)
{
AZUtils.printObject(response.body());
}
@Override
public void onFailure(Throwable t) {
t.printStackTrace();
}
});
add this code to your project
public static class Extension {
public static string TextAfter(this string value ,string search) {
return value.Substring(value.IndexOf(search) + search.Length);
}
}
then use
"code : string text ".TextAfter(":")
I was facing with this problem some time ago and I found java.util.LinkedList
is best for my case. It has several methods, with different namings, but they're doing what is needed:
push() -> LinkedList.addLast(); // Or just LinkedList.add();
pop() -> LinkedList.pollLast();
shift() -> LinkedList.pollFirst();
unshift() -> LinkedList.addFirst();
Variation of Aaron's answer. Using sed without temporary files
#!/bin/bash
VERSION=1.0.0
IMAGE=company/image
ID=$(docker build -t ${IMAGE} . | tail -1 | sed 's/.*Successfully built \(.*\)$/\1/')
docker tag ${ID} ${IMAGE}:${VERSION}
docker tag -f ${ID} ${IMAGE}:latest
Here's a custom theme to make the ggplot2 background white and a bunch of other changes that's good for publications and posters. Just tack on +mytheme. If you want to add or change options by +theme after +mytheme, it will just replace those options from +mytheme.
library(ggplot2)
library(cowplot)
theme_set(theme_cowplot())
mytheme = list(
theme_classic()+
theme(panel.background = element_blank(),strip.background = element_rect(colour=NA, fill=NA),panel.border = element_rect(fill = NA, color = "black"),
legend.title = element_blank(),legend.position="bottom", strip.text = element_text(face="bold", size=9),
axis.text=element_text(face="bold"),axis.title = element_text(face="bold"),plot.title = element_text(face = "bold", hjust = 0.5,size=13))
)
ggplot(data=data.frame(a=c(1,2,3), b=c(2,3,4)), aes(x=a, y=b)) + mytheme + geom_line()
Here's a simple working solution:
@-moz-keyframes spin { 100% { -moz-transform: rotate(360deg); } }
@-webkit-keyframes spin { 100% { -webkit-transform: rotate(360deg); } }
@keyframes spin { 100% { -webkit-transform: rotate(360deg); transform:rotate(360deg); } }
.elem:hover {
-webkit-animation:spin 1.5s linear infinite;
-moz-animation:spin 1.5s linear infinite;
animation:spin 1.5s linear infinite;
}
For my case, this error was triggered because of a huge select query (hundreds of thousands of returned results).
It arose immediately after adding millions of records in my Database to test the scalability of WordPress, so it was the only probable reason for me.
As OP mention about raw_input - that means he want cli solution. Linux: curses is what you want (windows PDCurses). Curses, is an graphical API for cli software, you can achieve more than just detect key events.
This code will detect keys until new line is pressed.
import curses
import os
def main(win):
win.nodelay(True)
key=""
win.clear()
win.addstr("Detected key:")
while 1:
try:
key = win.getkey()
win.clear()
win.addstr("Detected key:")
win.addstr(str(key))
if key == os.linesep:
break
except Exception as e:
# No input
pass
curses.wrapper(main)
The following works on all browsers for my 200 figures, for any width percentage -- despite being illegal. Jukka said 'Use it anyway.' (The class just floats the image left or right and sets margins.) I can't imagine why this isn't the standard approach!
<img class="fl" width="66%"
src="A-Images/0.5_Saltation.jpg"
alt="Schematic models of chromosomes ..." />
Change the window width and the image scales obligingly.
Add this attribute to you activity in manifest file. android:noHistory="true"
While doing "figure(1), figure(2),..." will solve the problem in most cases, it will not solve them in all cases. Suppose you have a bunch of MATLAB figures on your desktop and how many you have open varies from time to time before you run your code. Using the answers provided, you will overwrite these figures, which you may not want. The easy workaround is to just use the command "figure" before you plot.
Example: you have five figures on your desktop from a previous script you ran and you use
figure(1);
plot(...)
figure(2);
plot(...)
You just plotted over the figures on your desktop. However the code
figure;
plot(...)
figure;
plot(...)
just created figures 6 and 7 with your desired plots and left your previous plots 1-5 alone.
This worked for me:
min-height: 14px;
height: 14px;
list( map( lambda x: x[4][0], socket.getaddrinfo( \
'www.example.com.',22,type=socket.SOCK_STREAM)))
gives you a list of the addresses for www.example.com. (ipv4 and ipv6)
Just figured it out in Oracle Java the environmental variable is called: JAVA_TOOL_OPTIONS
rather than JAVA_OPTS
The brackets can be used when column names are reserved words.
If you are programatically generating the SQL statement from a collection of column names you don't control, then you can avoid problems by always using the brackets.
I am not sure I fully understand the problem, but pulling an existing branch is done like this (at least it works for me :)
git pull origin BRANCH
This is assuming that your local branch is created off of the origin/BRANCH.
You should add System.configuration dll as reference and use System.Configuration.ConfigurationManager.AppSettings["configFile"].ToString
Don't forget to add using
statement at the beginning. Hope it will help.
A full training pass over the entire dataset such that each example has been seen once. Thus, an epoch represents N/batch size training iterations, where N is the total number of examples.
A single update of a model's weights during training. An iteration consists of computing the gradients of the parameters with respect to the loss on a single batch of data.
as bonus:
The set of examples used in one iteration (that is, one gradient update) of model training.
See also batch size.
source: https://developers.google.com/machine-learning/glossary/
This is a slightly enhanced version of previous answers.
CancellationToken
for the original task, and when timeout occurs, you get TimeoutException
instead of OperationCanceledException
.async Task<TResult> CancelAfterAsync<TResult>(
Func<CancellationToken, Task<TResult>> startTask,
TimeSpan timeout, CancellationToken cancellationToken)
{
using (var timeoutCancellation = new CancellationTokenSource())
using (var combinedCancellation = CancellationTokenSource
.CreateLinkedTokenSource(cancellationToken, timeoutCancellation.Token))
{
var originalTask = startTask(combinedCancellation.Token);
var delayTask = Task.Delay(timeout, timeoutCancellation.Token);
var completedTask = await Task.WhenAny(originalTask, delayTask);
// Cancel timeout to stop either task:
// - Either the original task completed, so we need to cancel the delay task.
// - Or the timeout expired, so we need to cancel the original task.
// Canceling will not affect a task, that is already completed.
timeoutCancellation.Cancel();
if (completedTask == originalTask)
{
// original task completed
return await originalTask;
}
else
{
// timeout
throw new TimeoutException();
}
}
}
InnerCallAsync
may take a long time to complete. CallAsync
wraps it with a timeout.
async Task<int> CallAsync(CancellationToken cancellationToken)
{
var timeout = TimeSpan.FromMinutes(1);
int result = await CancelAfterAsync(ct => InnerCallAsync(ct), timeout,
cancellationToken);
return result;
}
async Task<int> InnerCallAsync(CancellationToken cancellationToken)
{
return 42;
}
arrays:
malloc
);sizeof
(hence the common idiom sizeof(arr)/sizeof(*arr)
, that however fails silently when used inadvertently on a pointer);std::vector
:
&vec[0]
is guaranteed to work as expected);begin()
/end()
methods, the usual STL typedef
s, ...)Also consider the "modern alternative" to arrays - std::array
; I already described in another answer the difference between std::vector
and std::array
, you may want to have a look at it.
Check first your class loader.
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
if (classLoader == null) {
classLoader = Class.class.getClassLoader();
}
classLoader.getResourceAsStream("xmlFileNameInJarFile.xml");
// xml file location at xxx.jar
// + folder
// + folder
// xmlFileNameInJarFile.xml
Best function to detect associative array (hash array)
<?php
function is_assoc($arr) { return (array_values($arr) !== $arr); }
?>
https://angular.io/guide/user-input - there's a simple example .
( If your url is correct and still get that error messege ) Do following steps to setup the Classpath in netbeans,
Now you will see that .jar file will be included under the libraries. Now you will not need to use the line, Class.forName("com.mysql.jdbc.Driver"); also.
If above method did not work, check the mysql-connector version (eg:- 5.1.35) and try a newer or a suitable version for you.
In order to run scripts, you should write the "python test.py" command in the command prompt, and not within the python shell. also, the test.py file should be at the path you run from in the cli.
List<int> list = new List<int>();
int[] intList = list.ToArray();
is it your solution?
That doesn't work because, judging by the rest of the code, the initial value of the text input is "Default text" - which is more than one character, and so your if
condition is always true.
The simplest way to make it work, it seems to me, is to account for this case:
var value = $(this).val();
if ( value.length > 0 && value != "Default text" ) ...
The answers given were not totally complete if multiple sourcepath and subpackages have to be processed.
The following command line will process all the packages under com and LOR (lord of the rings) located into /home/rudy/IdeaProjects/demo/src/main/java and /home/rudy/IdeaProjects/demo/src/test/java/
Please note:
rudy@rudy-ThinkPad-T590:~$ javadoc -d /home/rudy/IdeaProjects/demo_doc
-sourcepath /home/rudy/IdeaProjects/demo/src/main/java/
:/home/rudy/IdeaProjects/demo/src/test/java/
-subpackages com:LOR
-private
rudy@rudy-ThinkPad-T590:~/IdeaProjects/demo/src/main/java$ ls -R
.: com LOR
./com: example
./com/example: demo
./com/example/demo: DemowApplication.java
./LOR: Race.java TolkienCharacter.java
rudy@rudy-ThinkPad-T590:~/IdeaProjects/demo/src/test/java$ ls -R
.: com
./com: example
./com/example: demo
./com/example/demo: AssertJTest.java DemowApplicationTests.java
I got this error after change a loop in my program, let`s see:
for ...
for ...
x_batch.append(one_hot(int_word, vocab_size))
y_batch.append(one_hot(int_nb, vocab_size, value))
...
...
if ...
x_batch = np.asarray(x_batch)
y_batch = np.asarray(y_batch)
...
In fact, I was reusing the variable and forgot to reset them inside the external loop, like the comment of John Lyon:
for ...
x_batch = []
y_batch = []
for ...
x_batch.append(one_hot(int_word, vocab_size))
y_batch.append(one_hot(int_nb, vocab_size, value))
...
...
if ...
x_batch = np.asarray(x_batch)
y_batch = np.asarray(y_batch)
...
Then, check if you are using np.asarray() or something like that.
out
specifies that the parameter is an output parameters, i.e. it has no value until it is explicitly set by the method.
ref
specifies that the value is a reference that has a value, and whose value you can change inside the method.
You can do it in a single command:
git fetch --all && git reset --hard origin/master
Or in a pair of commands:
git fetch --all
git reset --hard origin/master
Note than you will lose ALL your local changes
I second Hightechrider: there is a specialized Url class already built for you.
I must also point out, however, that the PHP's replaceAll uses regular expressions for search pattern, which you can do in .NET as well - look at the RegEx class.
Above suggestions didn't worked for me. I got it running on my windows, using inspiration from http://butlerccwebdev.net/support/testingserver/vhosts-setup-win.html
For Http inside httpd-vhosts.conf
<Directory "D:/Projects">
AllowOverride All
Require all granted
</Directory>
##Letzgrow
<VirtualHost *:80>
DocumentRoot "D:/Projects/letzgrow"
ServerName letz.dev
ServerAlias letz.dev
</VirtualHost>
For using Https (Open SSL) inside httpd-ssl.conf
<Directory "D:/Projects">
AllowOverride All
Require all granted
</Directory>
##Letzgrow
<VirtualHost *:443>
DocumentRoot "D:/Projects/letzgrow"
ServerName letz.dev
ServerAlias letz.dev
</VirtualHost>
Hope it helps someone !!
One interesting thing that I came across is the fact that you can have a capturing group inside a non-capturing group. Have a look at below regex for matching web urls:
var parse_url_regex = /^(?:([A-Za-z]+):)(\/{0,3})([0-9.\-A-Za-z]+)(?::(\d+))?(?:\/([^?#]*))?(?:\?([^#]*))?(?:#(.*))?$/;
Input url string:
var url = "http://www.ora.com:80/goodparts?q#fragment";
The first group in my regex (?:([A-Za-z]+):)
is a non-capturing group which matches the protocol scheme and colon :
character i.e. http:
but when I was running below code, I was seeing the 1st index of the returned array was containing the string http
when I was thinking that http
and colon :
both will not get reported as they are inside a non-capturing group.
console.debug(parse_url_regex.exec(url));
I thought if the first group (?:([A-Za-z]+):)
is a non-capturing group then why it is returning http
string in the output array.
So if you notice that there is a nested group ([A-Za-z]+)
inside the non-capturing group. That nested group ([A-Za-z]+)
is a capturing group (not having ?:
at the beginning) in itself inside a non-capturing group (?:([A-Za-z]+):)
. That's why the text http
still gets captured but the colon :
character which is inside the non-capturing group but outside the capturing group doesn't get reported in the output array.
As others have pointed out one could just delete all the files in the repo and then check them out. I prefer this method and it can be done with the code below
git ls-files -z | xargs -0 rm
git checkout -- .
or one line
git ls-files -z | xargs -0 rm ; git checkout -- .
I use it all the time and haven't found any down sides yet!
For some further explanation, the -z
appends a null character onto the end of each entry output by ls-files
, and the -0
tells xargs
to delimit the output it was receiving by those null characters.
You can get detail error by using responseText property.
$.ajaxSetup({
error: function(xhr, status, error) {
alert("An AJAX error occured: " + status + "\nError: " + error + "\nError detail: " + xhr.responseText);
}
});
I know this is not a solution for OP, but since I'm sure there are many other use cases here, I thought I would share.
I've had problems with all the code examples in these answers but then I found : http://www.robotronic.de/runasspcEn.html
It not only allows you to run as admin, it checks the file to make sure it has not been tampered with and stores the needed information securely. I'll admit it's not the most obvious tool to figure out how to use but for those of us writing code it should be simple enough.
The data is UTF-8 encoded bytes escaped with URL quoting, so you want to decode, with urllib.parse.unquote()
, which handles decoding from percent-encoded data to UTF-8 bytes and then to text, transparently:
from urllib.parse import unquote
url = unquote(url)
Demo:
>>> from urllib.parse import unquote
>>> url = 'example.com?title=%D0%BF%D1%80%D0%B0%D0%B2%D0%BE%D0%B2%D0%B0%D1%8F+%D0%B7%D0%B0%D1%89%D0%B8%D1%82%D0%B0'
>>> unquote(url)
'example.com?title=????????+??????'
The Python 2 equivalent is urllib.unquote()
, but this returns a bytestring, so you'd have to decode manually:
from urllib import unquote
url = unquote(url).decode('utf8')