Using numpy, you can do:
y = x.astype(int)
If you were using a non-numpy array, you could use a list comprehension:
y = [int(val) for val in x]
If you want to start at the "application root" as you describe right click on the top level Default.aspx page and choose set as start page. Hit F5 and you're done.
If you want to start at a different controller action see Mark's answer.
There is a built-in Windows tool for that:
dir /s 'FolderName'
This will print a lot of unnecessary information but the end will be the folder size like this:
Total Files Listed:
12468 File(s) 182,236,556 bytes
If you need to include hidden folders add /a
.
You can try this direct VBA
approach which doesn't require HEX editing. It will work for any files (*.xls, *.xlsm, *.xlam ...).
Tested and works on:
Excel 2007
Excel 2010
Excel 2013 - 32 bit version
Excel 2016 - 32 bit version
Looking for 64 bit version? See this answer
I will try my best to explain how it works - please excuse my English.
Please backup your files first!
Create a new xlsm file and store this code in Module1
code credited to Siwtom (nick name), a Vietnamese developer
Option Explicit
Private Const PAGE_EXECUTE_READWRITE = &H40
Private Declare Sub MoveMemory Lib "kernel32" Alias "RtlMoveMemory" _
(Destination As Long, Source As Long, ByVal Length As Long)
Private Declare Function VirtualProtect Lib "kernel32" (lpAddress As Long, _
ByVal dwSize As Long, ByVal flNewProtect As Long, lpflOldProtect As Long) As Long
Private Declare Function GetModuleHandleA Lib "kernel32" (ByVal lpModuleName As String) As Long
Private Declare Function GetProcAddress Lib "kernel32" (ByVal hModule As Long, _
ByVal lpProcName As String) As Long
Private Declare Function DialogBoxParam Lib "user32" Alias "DialogBoxParamA" (ByVal hInstance As Long, _
ByVal pTemplateName As Long, ByVal hWndParent As Long, _
ByVal lpDialogFunc As Long, ByVal dwInitParam As Long) As Integer
Dim HookBytes(0 To 5) As Byte
Dim OriginBytes(0 To 5) As Byte
Dim pFunc As Long
Dim Flag As Boolean
Private Function GetPtr(ByVal Value As Long) As Long
GetPtr = Value
End Function
Public Sub RecoverBytes()
If Flag Then MoveMemory ByVal pFunc, ByVal VarPtr(OriginBytes(0)), 6
End Sub
Public Function Hook() As Boolean
Dim TmpBytes(0 To 5) As Byte
Dim p As Long
Dim OriginProtect As Long
Hook = False
pFunc = GetProcAddress(GetModuleHandleA("user32.dll"), "DialogBoxParamA")
If VirtualProtect(ByVal pFunc, 6, PAGE_EXECUTE_READWRITE, OriginProtect) <> 0 Then
MoveMemory ByVal VarPtr(TmpBytes(0)), ByVal pFunc, 6
If TmpBytes(0) <> &H68 Then
MoveMemory ByVal VarPtr(OriginBytes(0)), ByVal pFunc, 6
p = GetPtr(AddressOf MyDialogBoxParam)
HookBytes(0) = &H68
MoveMemory ByVal VarPtr(HookBytes(1)), ByVal VarPtr(p), 4
HookBytes(5) = &HC3
MoveMemory ByVal pFunc, ByVal VarPtr(HookBytes(0)), 6
Flag = True
Hook = True
End If
End If
End Function
Private Function MyDialogBoxParam(ByVal hInstance As Long, _
ByVal pTemplateName As Long, ByVal hWndParent As Long, _
ByVal lpDialogFunc As Long, ByVal dwInitParam As Long) As Integer
If pTemplateName = 4070 Then
MyDialogBoxParam = 1
Else
RecoverBytes
MyDialogBoxParam = DialogBoxParam(hInstance, pTemplateName, _
hWndParent, lpDialogFunc, dwInitParam)
Hook
End If
End Function
Paste this code under the above code in Module1 and run it
Sub unprotected()
If Hook Then
MsgBox "VBA Project is unprotected!", vbInformation, "*****"
End If
End Sub
Come back to your VBA Projects and enjoy.
on windows 10, Notepad 7.8.5, i found this solution to convert from CRLF to LF.
Edit > Format end of line
and choose either Windows(CR+LF)
or Unix(LF)
For those who need the input file to open directly the camera, you just have to declare capture
parameter to the input file, like this :
<input type="file" accept="image/*" capture>
In App.js
import {useHistory } from "react-router-dom";
const TheContext = React.createContext(null);
const App = () => {
const history = useHistory();
<TheContext.Provider value={{ history, user }}>
<Switch>
<Route exact path="/" render={(props) => <Home {...props} />} />
<Route
exact
path="/sign-up"
render={(props) => <SignUp {...props} setUser={setUser} />}
/> ...
Then in a child component :
const Welcome = () => {
const {user, history} = React.useContext(TheContext);
....
I think the reason AngularJS does not say much about form submission because it depends more on 'two-way data binding'. In traditional html development you had one way data binding, i.e. once DOM rendered any changes you make to DOM element did not reflect in JS Object, however in AngularJS it works both way. Hence there's in fact no need to form submission. I have done a mid sized application using AngularJS without the need to form submission. If you are keen to submit form you can write a directive wrapping up your form which handles ENTER keydown and SUBMIT button click events and call form.submit().
If you want the sample source code of such a directive, please let me know by commenting on this. I figured out it would a simple directive that you can write yourself.
The only way to really protect your php-applications from other, is to not share the source code. If you post you code somewhere online, or send it to you customers by some medium, other people than you have access to the code.
You could add an unique watermark to every single copy of your code. That way you can trace leaks back to a singe customer. (But will that help you, since the code already are outside of your control?)
Most code I see comes with a licence and maybe a warranty. A line at the top of the script telling people not to alter the script, will maybe be enought. Self; when I find non-open source code, I won't use it in my projects. Maybe I'm a bit dupe, but I expect ppl not to use my none-OSS code!
Since you are not worried about IE, why not just use css transitions to provide the animation and jQuery to change the classes. Live example: http://jsfiddle.net/tw16/JfK6N/
#someDiv{
-webkit-transition: all 0.5s ease;
-moz-transition: all 0.5s ease;
-o-transition: all 0.5s ease;
transition: all 0.5s ease;
}
The \includegraphics
function has a page
option for inserting a specific page of a PDF file as graphs. The default is one, but you can change it.
\includegraphics[scale=0.75,page=2]{multipage.pdf}
You can find more here.
I think you're using the wrong approach. You should set the value
attribute of your input elements. Check the docs for .val() for examples of setting and returning the .val() of input elements.
ie.
<input type="radio" runat="server" name="testGroup" value="test2" />
return $('input:radio[name=testGroup]:checked').val() == 'test2';
You can use Array.IndexOf()
- note that it will return -1 if the element has not been found and you have to handle this case.
int index = Array.IndexOf(stringArray, value);
A key pair (the private and public keys) will have the same fingerprint; so in the case you can't remember which private key belong to which public key, find the match by comparing their fingerprints.
The most voted answer by Marvin Vinto provides the fingerprint of a public SSH key file. The fingerprint of the corresponding private SSH key can also be queried, but it requires a longer series of step, as shown below.
Load the SSH agent, if you haven't done so. The easiest way is to invoke
$ ssh-agent bash
or
$ ssh-agent tcsh
(or another shell you use).
Load the private key you want to test:
$ ssh-add /path/to/your-ssh-private-key
You will be asked to enter the passphrase if the key is password-protected.
Now, as others have said, type
$ ssh-add -l
1024 fd:bc:8a:81:58:8f:2c:78:86:a2:cf:02:40:7d:9d:3c you@yourhost (DSA)
fd:bc:...
is the fingerprint you are after. If there are multiple keys, multiple lines will be printed, and the last line contains the fingerprint of the last loaded key.
If you want to stop the agent (i.e., if you invoked step 1 above), then simply type `exit' on the shell, and you'll be back on the shell prior to the loading of ssh agent.
I do not add new information, but hopefully this answer is clear to users of all levels.
NOTE: Not sure if the syntax I'm using in this answer was available when the older answers were written, but I think that this is a better approach on how to solve the example mentioned in this question.
I've had some issues related to this topic (overwriting interface properties), and this is how I'm handling it:
You can even use choose a default
value for the generic parameter as you can see in <T extends number | SOME_OBJECT = number>
type SOME_OBJECT = { foo: "bar" }
interface INTERFACE_A <T extends number | SOME_OBJECT = number> {
property: T;
}
type A_NUMBER = INTERFACE_A; // USES THE default = number TYPE. SAME AS INTERFACE_A<number>
type A_SOME_OBJECT = INTERFACE_A<SOME_OBJECT> // MAKES { property: SOME_OBJECT }
And this is the result:
const aNumber: A_NUMBER = {
property: 111 // THIS EXPECTS A NUMBER
}
const anObject: A_SOME_OBJECT = {
property: { // THIS EXPECTS SOME_OBJECT
foo: "bar"
}
}
It's the array that's causing trouble in:
void print_graph(g_node graph_node[], double weight[][], int nodes);
The second and subsequent dimensions must be given:
void print_graph(g_node graph_node[], double weight[][32], int nodes);
Or you can just give a pointer to pointer:
void print_graph(g_node graph_node[], double **weight, int nodes);
However, although they look similar, those are very different internally.
If you're using C99, you can use variably-qualified arrays. Quoting an example from the C99 standard (section §6.7.5.2 Array Declarators):
void fvla(int m, int C[m][m]); // valid: VLA with prototype scope
void fvla(int m, int C[m][m]) // valid: adjusted to auto pointer to VLA
{
typedef int VLA[m][m]; // valid: block scope typedef VLA
struct tag {
int (*y)[n]; // invalid: y not ordinary identifier
int z[n]; // invalid: z not ordinary identifier
};
int D[m]; // valid: auto VLA
static int E[m]; // invalid: static block scope VLA
extern int F[m]; // invalid: F has linkage and is VLA
int (*s)[m]; // valid: auto pointer to VLA
extern int (*r)[m]; // invalid: r has linkage and points to VLA
static int (*q)[m] = &B; // valid: q is a static block pointer to VLA
}
[...] In my main(), the variable I am trying to pass into the function is a
double array[][]
, so how would I pass that into the function? Passingarray[0][0]
into it gives me incompatible argument type, as does&array
and&array[0][0]
.
In your main()
, the variable should be:
double array[10][20];
or something faintly similar; maybe
double array[][20] = { { 1.0, 0.0, ... }, ... };
You should be able to pass that with code like this:
typedef struct graph_node
{
int X;
int Y;
int active;
} g_node;
void print_graph(g_node graph_node[], double weight[][20], int nodes);
int main(void)
{
g_node g[10];
double array[10][20];
int n = 10;
print_graph(g, array, n);
return 0;
}
That compiles (to object code) cleanly with GCC 4.2 (i686-apple-darwin11-llvm-gcc-4.2 (GCC) 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2336.9.00)) and also with GCC 4.7.0 on Mac OS X 10.7.3 using the command line:
/usr/bin/gcc -O3 -g -std=c99 -Wall -Wextra -c zzz.c
It's simple. Just change the port. Use 3268 instead of 389. If your domain name DOMAIN.LOCAL, in search put DC=DOMAIN,DC=LOCAL
Port 3268: This port is used for queries that are specifically targeted for the global catalog. LDAP requests sent to port 3268 can be used to search objects in the entire forest. However, only the attributes marked for replication to the global catalog can be returned.
Port 389: This port is used for requesting information from the Domain Controller. LDAP requests sent to port 389 can be used to search objects only within the global catalog’s home domain. However, the application can possible to obtain all of the attributes searched objects.
Angular 1.3 provides $watchGroup specifically for this purpose:
https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$watchGroup
This seems to provide the same ultimate result as a standard $watch on an array of expressions. I like it because it makes the intention clearer in the code.
if ("true".equals(value) || "false".equals(value)) {
// do something
} else {
// do something else
}
Another point of view
First, you can declare an anonymous function:
var foo = function(msg){
alert(msg);
}
Then you call it:
foo ('Few');
Because foo = function(msg){alert(msg);} so you can replace foo as:
function(msg){
alert(msg);
} ('Few');
But you should wrap your entire anonymous function inside pair of braces to avoid syntax error of declaring function when parsing. Then we have,
(function(msg){
alert(msg);
}) ('Few');
By this way, It's easy understand for me.
This is, unfortunately a quite common problem on Windows where the icons are either not updated or rather disappearing. I find it quite annoying. It usually is fixed by either refreshing the Windows folder (F5) or, by doing a SVN Clean up,
Right click on the folder -> TortoiseSVN -> Clean up...
Select Clean up working copy status
I have never been able to solve this permanently, this is only a work-around. Keeping TortoiseSVN on the latest version may or may not help.
Note that the clean up will only clean up your local working copy, it wont do anything to the actual repository. Its a safe operation.
Apparently this is not enough according to your comment. Do you have lots of other programs that are also using overlay icons? If so maybe you can find a solution in this thread: TortoiseSVN icons not showing up under Windows 7? The second most voted answer also deals with network drives etc. Its a good read.
Also, have you rebooted your computer after the install? From the TortoiseSVN FAQ:
You rebooted your PC of course after the installation? If you haven't please do so now. TortoiseSVN is a windows Explorer Shell extension and will be loaded together with Explorer.
...
Otherwise, try doing a repair install (and reboot of course).
it was hard to solve but i did it look go to C:\Users(user name)
delete .gradle file its you didn't see it it may be in hidden files so if you use windows 7 right click then click on properties and click on hidden to be not checked
then the file will appear then delete it i hope this works
Make sure you have mod_rewrite enabled.
restart apache
and clear cookies of your browser for read again at .htaccess
VM Player runs a virtual instance, but can't create the vm. [Edit: Now it can.] Workstation allows for the creation and administration of virtual machines. If you have a second machine, you can create the vm on one and run it with the player the other machine. I bought Workstation and I use it setup testing vms that the player runs. Hope this explains it for you.
Edit: According to the FAQ:
VMware Workstation is much more advanced and comes with powerful features including snapshots, cloning, remote connections to vSphere, sharing VMs, advanced Virtual Machines settings and much more. Workstation is designed to be used by technical professionals such as developers, quality assurance engineers, systems engineers, IT administrators, technical support representatives, trainers, etc.
You can convert varchars to floats, and you can do it in the manner you have expressed. Your varchar must not be a numeric value. There must be something else in it. You can use IsNumeric to test it. See this:
declare @thing varchar(100)
select @thing = '122.332'
--This returns 1 since it is numeric.
select isnumeric(@thing)
--This converts just fine.
select convert(float,@thing)
select @thing = '122.332.'
--This returns 0 since it is not numeric.
select isnumeric(@thing)
--This convert throws.
select convert(float,@thing)
Export should be specific about which version of GCC/G++ to use, because if user had multiple compiler version, it would not compile successfully.
export CC=path_of_gcc/gcc-version
export CXX=path_of_g++/g++-version
cmake path_of_project_contain_CMakeList.txt
make
In case project use C++11 this can be handled by using -std=C++-11
flag in CMakeList.txt
if ($("input").is(":not(:checked)"))
AFAIK, this should work, tested against the latest stable jQuery (1.2.6).
Plattform-specific, but also theoretical exec vectors:
And there are many more disguising methods:
Renaming .bashrc
to .profile
(or soft-linking the latter to the former) should also do the trick. See here.
instead of overwriting, create it as different css and call it in your element as other css(multiple css).
Something like:
.flex-control-thumbs li
{ margin: 0; }
Internal CSS:
.additional li
{width: 25%; float: left;}
<ul class="flex-control-thumbs additional"> </ul> /* assuming parent is ul */
chart.series[0].setData(data,true);
The setData
method itself will call the redraw method
Try indexOf
if (foo.indexOf("franky") >= 0)
{
...
}
You can also try search (for regular expressions)
if (foo.search("franky") >= 0)
{
...
}
Even I come across same problem, not able to find active connections to my_db to kill it but still shows same error. I end up disconnecting all possible SSMS connections for any database on the Server, create a new connection from SSMS and change it to Multi user.
-- Actual Code to change my_db to multi user mode
USE MASTER;
GO
ALTER DATABASE [my_db] SET MULTI_USER
Note: This seems to be a possible bug in SQL Server 2005!
Use a foreach loop, it loops through all the key=>value pairs:
foreach($array as $key=>$value){
print "$key holds $value\n";
}
Or to answer your question completely:
foreach($array as $value){
print $value."\n";
}
For System.Timers.Timer, on separate thread, if SynchronizingObject is not set.
static System.Timers.Timer DummyTimer = null;
static void Main(string[] args)
{
try
{
Console.WriteLine("Main Thread Id: " + System.Threading.Thread.CurrentThread.ManagedThreadId);
DummyTimer = new System.Timers.Timer(1000 * 5); // 5 sec interval
DummyTimer.Enabled = true;
DummyTimer.Elapsed += new System.Timers.ElapsedEventHandler(OnDummyTimerFired);
DummyTimer.AutoReset = true;
DummyTimer.Start();
Console.WriteLine("Hit any key to exit");
Console.ReadLine();
}
catch (Exception Ex)
{
Console.WriteLine(Ex.Message);
}
return;
}
static void OnDummyTimerFired(object Sender, System.Timers.ElapsedEventArgs e)
{
Console.WriteLine(System.Threading.Thread.CurrentThread.ManagedThreadId);
return;
}
Output you'd see if DummyTimer fired on 5 seconds interval:
Main Thread Id: 9
12
12
12
12
12
...
So, as seen, OnDummyTimerFired is executed on Workers thread.
No, further complication - If you reduce interval to say 10 ms,
Main Thread Id: 9
11
13
12
22
17
...
This is because if prev execution of OnDummyTimerFired isn't done when next tick is fired, then .NET would create a new thread to do this job.
Complicating things further, "The System.Timers.Timer class provides an easy way to deal with this dilemma—it exposes a public SynchronizingObject property. Setting this property to an instance of a Windows Form (or a control on a Windows Form) will ensure that the code in your Elapsed event handler runs on the same thread on which the SynchronizingObject was instantiated."
A simple example without classes:
from tkinter import *
master = Tk()
# Create this method before you create the entry
def return_entry(en):
"""Gets and prints the content of the entry"""
content = entry.get()
print(content)
Label(master, text="Input: ").grid(row=0, sticky=W)
entry = Entry(master)
entry.grid(row=0, column=1)
# Connect the entry with the return button
entry.bind('<Return>', return_entry)
mainloop()
In C language, character literal is not a char
type. C considers character literal as integer. So, there is no difference between sizeof('a')
and sizeof(1)
.
So, the sizeof character literal is equal to sizeof integer in C.
In C++ language, character literal is type of char
. The cppreference say's:
1) narrow character literal or ordinary character literal, e.g.
'a'
or'\n'
or'\13'
. Such literal has typechar
and the value equal to the representation of c-char in the execution character set. If c-char is not representable as a single byte in the execution character set, the literal has type int and implementation-defined value.
So, in C++ character literal is a type of char
. so, size of character literal in C++ is one byte.
Alos, In your programs, you have used wrong format specifier for sizeof
operator.
C11 §7.21.6.1 (P9) :
If a conversion specification is invalid, the behavior is undefined.275) If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.
So, you should use %zu
format specifier instead of %d
, otherwise it is undefined behaviour in C.
Normally adding the binding redirect should solve this problem, but it was not working for me. After a few hours of banging my head against the wall, I realized that there was an xmlns attribute causing problems in my web.config. After removing the xmlns attribute from the configuration node in Web.config, the binding redirects worked as expected.
INSERT INTO Test([col1],[col2]) (
SELECT
a.Name AS [col1],
b.sub AS [col2]
FROM IdTable b
INNER JOIN Nametable a ON b.no = a.no
)
You can Use ngValue
. ngValue
passes sting and object both.
Pass as Object:
<select (change)="onItemChange($event.value)">
<option *ngFor="#obj of arr" [ngValue]="obj.value">
{{obj.value}}
</option>
</select>
Pass as String:
<select (change)="onItemChange($event.value)">
<option *ngFor="#obj of arr" [ngValue]="obj">
{{obj.value}}
</option>
</select>
Make sure to use the latest npm version while installing packages using npm.
While installing JavaScript, mention the latest version of NodeJS. For example, while installing JavaScript using devtools, use the below code:
devtools i --javascript nodejs:10.15.1
This will download and install the mentioned NodeJS version. Try installing the packages with npm after updating the version. This worked for me.
Sending an HTTP POST request using file_get_contents
is not that hard, actually : as you guessed, you have to use the $context
parameter.
There's an example given in the PHP manual, at this page : HTTP context options (quoting) :
$postdata = http_build_query(
array(
'var1' => 'some content',
'var2' => 'doh'
)
);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-Type: application/x-www-form-urlencoded',
'content' => $postdata
)
);
$context = stream_context_create($opts);
$result = file_get_contents('http://example.com/submit.php', false, $context);
Basically, you have to create a stream, with the right options (there is a full list on that page), and use it as the third parameter to file_get_contents
-- nothing more ;-)
As a sidenote : generally speaking, to send HTTP POST requests, we tend to use curl, which provides a lot of options an all -- but streams are one of the nice things of PHP that nobody knows about... too bad...
pandas 0.21 introduces new functions for Parquet:
pd.read_parquet('example_pa.parquet', engine='pyarrow')
or
pd.read_parquet('example_fp.parquet', engine='fastparquet')
The above link explains:
These engines are very similar and should read/write nearly identical parquet format files. These libraries differ by having different underlying dependencies (fastparquet by using numba, while pyarrow uses a c-library).
I had this problem because my entitlements file was malformed due to previous manual editing. I removed the wrongly formatted entitlement entry syntax and then i could click "fix" in the capabilities tab and Xcode added the entitlement to my file.
Here is an example of a properly formatted entitlements file ("Runner.entitlements
"):
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>aps-environment</key>
<string>development</string>
<key>com.apple.developer.applesignin</key>
<array>
<string>Default</string>
</array>
</dict>
</plist>
You can also pass the function of a struct, like:
package main
// define struct
type Apple struct {}
// return apple's color
func (Apple) GetColor() string {
return "Red"
}
func main () {
// instantiate
myApple := Apple{}
// put the func in a variable
theFunc := myApple.GetColor
// execute the variable as a function
color := theFunc()
print(color)
}
output will be "Red", check on the playground
With this solution, you probably can resolve all mobile clicks problems. Use only "click" function, but add z-index:99 to the element in css:
$("#test").on('click', function(){_x000D_
alert("CLICKED!")_x000D_
});
_x000D_
#test{ _x000D_
z-index:99;_x000D_
cursor:pointer;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>_x000D_
_x000D_
<div id="test">CLICK ME</div>
_x000D_
Credit:https://foundation.zurb.com/forum/posts/3258-buttons-not-clickable-on-iphone
Windows (unlike some other OS's, like Linux), uses CR+LF for line breaks:
CR = 13 = 0x0D = ^M = \r = carriage return
LF = 10 = 0x0A = ^J = \n = new line
The characters need to be in that order, if you want the line breaks to be consistently visible when copied to other Windows programs. So the Excel function would be:
=SUBSTITUTE(A1,",",CHAR(13) & CHAR(10))
Directory pull is available on new android tools. ( I don't know from which version it was added, but its working on latest ADT 21.1 )
adb pull /sdcard/Robotium-Screenshots
pull: building file list...
pull: /sdcard/Robotium-Screenshots/090313-110415.jpg -> ./090313-110415.jpg
pull: /sdcard/Robotium-Screenshots/090313-110412.jpg -> ./090313-110412.jpg
pull: /sdcard/Robotium-Screenshots/090313-110408.jpg -> ./090313-110408.jpg
pull: /sdcard/Robotium-Screenshots/090313-110406.jpg -> ./090313-110406.jpg
pull: /sdcard/Robotium-Screenshots/090313-110404.jpg -> ./090313-110404.jpg
5 files pulled. 0 files skipped.
61 KB/s (338736 bytes in 5.409s)
I did something else. I wanted to replace a word, in lists off lists, that contained phrases. I wanted to replace that sttring / word with a new word that will be a join between string and number, and that number / digit will indicate the position of the phrase / sublist / lists of lists.
That is, I replaced a string with a string and an incremental number that follow it.
myoldlist_1=[[' myoldword'],[''],['tttt myoldword'],['jjjj ddmyoldwordd']]
No_ofposition=[]
mynewlist_2=[]
for i in xrange(0,4,1):
mynewlist_2.append([x.replace('myoldword', "%s" % i+"_mynewword") for x in myoldlist_1[i]])
if len(mynewlist_2[i])>0:
No_ofposition.append(i)
mynewlist_2
No_ofposition
You can use index arrays, simply pass your ind_pos
as an index argument as below:
a = np.array([0,88,26,3,48,85,65,16,97,83,91])
ind_pos = np.array([1,5,7])
print(a[ind_pos])
# [88,85,16]
Index arrays do not necessarily have to be numpy arrays, they can be also be lists or any sequence-like object (though not tuples).
Try this
products.sort(function (a, b) {
return a.title.rendered - b.title.rendered;
});
OR
You can import lodash/underscore library, it has many build functions available for manipulating, filtering, sorting the array and all.
Using underscore: (below one is just an example)
import * as _ from 'underscore';
let sortedArray = _.sortBy(array, 'title');
This script searches for non-ascii characters in one column. It generates a string of all valid characters, here code point 32 to 127. Then it searches for rows that don't match the list:
declare @str varchar(128)
declare @i int
set @str = ''
set @i = 32
while @i <= 127
begin
set @str = @str + '|' + char(@i)
set @i = @i + 1
end
select col1
from YourTable
where col1 like '%[^' + @str + ']%' escape '|'
Add this extension method to your code:
public static Uri UrlOriginal(this HttpRequestBase request)
{
string hostHeader = request.Headers["host"];
return new Uri(string.Format("{0}://{1}{2}",
request.Url.Scheme,
hostHeader,
request.RawUrl));
}
And then you can execute it off the RequestContext.HttpContext.Request
property.
There is a bug (can be side-stepped, see below) in Asp.Net that arises on machines that use ports other than port 80 for the local website (a big issue if internal web sites are published via load-balancing on virtual IP and ports are used internally for publishing rules) whereby Asp.Net will always add the port on the AbsoluteUri
property - even if the original request does not use it.
This code ensures that the returned url is always equal to the Url the browser originally requested (including the port - as it would be included in the host header) before any load-balancing etc takes place.
At least, it does in our (rather convoluted!) environment :)
If there are any funky proxies in between that rewrite the host header, then this won't work either.
Update 30th July 2013
As mentioned by @KevinJones in comments below - the setting I mention in the next section has been documented here: http://msdn.microsoft.com/en-us/library/hh975440.aspx
Although I have to say I couldn't get it work when I tried it - but that could just be me making a typo or something.
Update 9th July 2012
I came across this a little while ago, and meant to update this answer, but never did. When an upvote just came in on this answer I thought I should do it now.
The 'bug' I mention in Asp.Net can be be controlled with an apparently undocumented appSettings value - called 'aspnet:UseHostHeaderForRequest'
- i.e:
<appSettings>
<add key="aspnet:UseHostHeaderForRequest" value="true" />
</appSettings>
I came across this while looking at HttpRequest.Url
in ILSpy - indicated by the --->
on the left of the following copy/paste from that ILSpy view:
public Uri Url
{
get
{
if (this._url == null && this._wr != null)
{
string text = this.QueryStringText;
if (!string.IsNullOrEmpty(text))
{
text = "?" + HttpEncoder.CollapsePercentUFromStringInternal(text,
this.QueryStringEncoding);
}
---> if (AppSettings.UseHostHeaderForRequestUrl)
{
string knownRequestHeader = this._wr.GetKnownRequestHeader(28);
try
{
if (!string.IsNullOrEmpty(knownRequestHeader))
{
this._url = new Uri(string.Concat(new string[]
{
this._wr.GetProtocol(),
"://",
knownRequestHeader,
this.Path,
text
}));
}
}
catch (UriFormatException)
{ }
}
if (this._url == null) { /* build from server name and port */
...
I personally haven't used it - it's undocumented and so therefore not guaranteed to stick around - however it might do the same thing that I mention above. To increase relevancy in search results - and to acknowledge somebody else who seeems to have discovered this - the 'aspnet:UseHostHeaderForRequest'
setting has also been mentioned by Nick Aceves on Twitter
This exact example is present on mozilla developers page:
As you can see it even allows you to create tooltips! :) Also, instead of embedding the actual text in your CSS, you may use content: attr(data-descr);
, and store it in data-descr="ADD"
attribute of your HTML tag (which is nice because you can e.g translate it)
CSS content
can only be usef with :after
and :before
pseudo-elements, so you can try to proceed with something like this:
.item a p.new-label span:after{
position: relative;
content: 'NEW'
}
.item:hover a p.new-label span:after {
content: 'ADD';
}
The CSS :after pseudo-element matches a virtual last child of the selected element. Typically used to add cosmetic content to an element, by using the content CSS property. This element is inline by default.
see this example
#include <stdlib.h> // for itoa() call
#include <stdio.h>
int main() {
int num = 145;
char buf[5];
// convert 123 to string [buf]
itoa(num, buf, 10);
// print our string
printf("%s\n", buf);
return 0;
}
see this link having other examples.
Well, if you're reading the data in as a list, just do np.array(map(float, list_of_strings))
(or equivalently, use a list comprehension). (In Python 3, you'll need to call list
on the map
return value if you use map
, since map
returns an iterator now.)
However, if it's already a numpy array of strings, there's a better way. Use astype()
.
import numpy as np
x = np.array(['1.1', '2.2', '3.3'])
y = x.astype(np.float)
Browsers can often tell the image type by sniffing out the meta information of the image. Also, there should be a space in that header:
header('Content-type: image/png');
Well here is something I used in several projects. It may look like a hack, but it works fine.
public class AttachedProperties : DependencyObject //adds a bindable DialogResult to window
{
public static readonly DependencyProperty DialogResultProperty =
DependencyProperty.RegisterAttached("DialogResult", typeof(bool?), typeof(AttachedProperties),
new PropertyMetaData(default(bool?), OnDialogResultChanged));
public bool? DialogResult
{
get { return (bool?)GetValue(DialogResultProperty); }
set { SetValue(DialogResultProperty, value); }
}
private static void OnDialogResultChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var window = d as Window;
if (window == null)
return;
window.DialogResult = (bool?)e.NewValue;
}
}
Now you can bind DialogResult
to a VM and set its value of a property. The Window
will close, when the value is set.
<!-- Assuming that the VM is bound to the DataContext and the bound VM has a property DialogResult -->
<Window someNs:AttachedProperties.DialogResult={Binding DialogResult} />
This is an abstract of what's running in our production environment
<Window x:Class="AC.Frontend.Controls.DialogControl.Dialog"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:DialogControl="clr-namespace:AC.Frontend.Controls.DialogControl"
xmlns:hlp="clr-namespace:AC.Frontend.Helper"
MinHeight="150" MinWidth="300" ResizeMode="NoResize" SizeToContent="WidthAndHeight"
WindowStartupLocation="CenterScreen" Title="{Binding Title}"
hlp:AttachedProperties.DialogResult="{Binding DialogResult}" WindowStyle="ToolWindow" ShowInTaskbar="True"
Language="{Binding UiCulture, Source={StaticResource Strings}}">
<!-- A lot more stuff here -->
</Window>
As you can see, I'm declaring the namespace xmlns:hlp="clr-namespace:AC.Frontend.Helper"
first and afterwards the binding hlp:AttachedProperties.DialogResult="{Binding DialogResult}"
.
The AttachedProperty
looks like this. It's not the same I posted yesterday, but IMHO it shouldn't have any effect.
public class AttachedProperties
{
#region DialogResult
public static readonly DependencyProperty DialogResultProperty =
DependencyProperty.RegisterAttached("DialogResult", typeof (bool?), typeof (AttachedProperties), new PropertyMetadata(default(bool?), OnDialogResultChanged));
private static void OnDialogResultChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var wnd = d as Window;
if (wnd == null)
return;
wnd.DialogResult = (bool?) e.NewValue;
}
public static bool? GetDialogResult(DependencyObject dp)
{
if (dp == null) throw new ArgumentNullException("dp");
return (bool?)dp.GetValue(DialogResultProperty);
}
public static void SetDialogResult(DependencyObject dp, object value)
{
if (dp == null) throw new ArgumentNullException("dp");
dp.SetValue(DialogResultProperty, value);
}
#endregion
}
With VSCode you can find the merge conflicts easily with the following UI.
(if you do not have the topbar, set "editor.codeLens": true
in User Preferences)
It indicates the current change that you have and incoming change from the server. This makes it easy to resolve the conflicts - just press the buttons above <<<< HEAD
.
If you have multiple changes and want to apply all of them at once - open command palette (View -> Command Palette) and start typing merge - multiple options will appear including Merge Conflict: Accept Incoming
, etc.
Or you can use reject
method
$newColection = $collection->reject(function($element) {
return $item->selected != true;
});
or pull
method
$selected = [];
foreach ($collection as $key => $item) {
if ($item->selected == true) {
$selected[] = $collection->pull($key);
}
}
If you are writing a DLL that encapsulates a ton of complex functionality into a simple public API, then “internal” is used on the class members which are not to be exposed publicly.
Hiding complexity (a.k.a. encapsulation) is the chief concept of quality software engineering.
Well, it looks like Access can't do aggregates in UPDATE queries. But it can do aggregates in SELECT queries. So create a query with a definition like:
SELECT func_id, min(tax_code) as MinOfTax_Code
FROM Functions
INNER JOIN Tax
ON (Functions.Func_Year = Tax.Tax_Year)
AND (Functions.Func_Pure <= Tax.Tax_ToPrice)
GROUP BY Func_Id
And save it as YourQuery. Now we have to work around another Access restriction. UPDATE queries can't operate on queries, but they can operate on multiple tables. So let's turn the query into a table with a Make Table query:
SELECT YourQuery.*
INTO MinOfTax_Code
FROM YourQuery
This stores the content of the view in a table called MinOfTax_Code. Now you can do an UPDATE query:
UPDATE MinOfTax_Code
INNER JOIN Functions ON MinOfTax_Code.func_id = Functions.Func_ID
SET Functions.Func_TaxRef = [MinOfTax_Code].[MinOfTax_Code]
Doing SQL in Access is a bit of a stretch, I'd look into Sql Server Express Edition for your project!
char ch = Character.MIN_VALUE;
The code above will initialize the variable ch
with the minimum value that a char can have (i.e. \u0000
).
preg_match("/iPhone|Android|iPad|iPod|webOS/", $_SERVER['HTTP_USER_AGENT'], $matches);
$os = current($matches);
switch($os){
case 'iPhone': /*do something...*/ break;
case 'Android': /*do something...*/ break;
case 'iPad': /*do something...*/ break;
case 'iPod': /*do something...*/ break;
case 'webOS': /*do something...*/ break;
}
Proxy can work in the following way.
Step1, configure client to use proxyHost:proxyPort.
Proxy is a TCP server that is listening on proxyHost:proxyPort. Browser opens connection with Proxy and sends Http request. Proxy parses this request and tries to detect "Host" header. This header will tell Proxy where to open connection.
Step 2: Proxy opens connection to the address specified in the "Host" header. Then it sends HTTP request to that remote server. Reads response.
Step 3: After response is read from remote HTTP server, Proxy sends the response through an earlier opened TCP connection with browser.
Schematically it will look like this:
Browser Proxy HTTP server
Open TCP connection
Send HTTP request ----------->
Read HTTP header
detect Host header
Send request to HTTP ----------->
Server
<-----------
Read response and send
<----------- it back to the browser
Render content
If a constant is needed in more than one class, I put it in config/initializers/contant.rb always in all caps (list of states below is truncated).
STATES = ['AK', 'AL', ... 'WI', 'WV', 'WY']
They are available through out the application except in model code as such:
<%= form.label :states, %>
<%= form.select :states, STATES, {} %>
To use the constant in a model, use attr_accessor to make the constant available.
class Customer < ActiveRecord::Base
attr_accessor :STATES
validates :state, inclusion: {in: STATES, message: "-- choose a State from the drop down list."}
end
If you are using bash with the extglob option enabled, you can remove just the trailing whitespace via:
shopt -s extglob
COMMAND=$'\nRE BOOT\r \n'
echo "|${COMMAND%%*([$'\t\r\n '])}|"
This outputs:
|
RE BOOT|
Or replace %% with ## to replace just the leading whitespace.
The awk solution is what I would use, but if you want to understand your problems with bash, here is a revised version of your script.
#!/bin/bash -vx
##config file with ip addresses like 10.10.10.1:80
file=config.txt
while read line ; do
##this line is not correct, should strip :port and store to ip var
ip=$( echo "$line" |cut -d\: -f1 )
ping $ip
done < ${file}
You could write your top line as
for line in $(cat $file) ; do ...
(but not recommended).
You needed command substitution $( ... )
to get the value assigned to $ip
reading lines from a file is usually considered more efficient with the while read line ... done < ${file}
pattern.
I hope this helps.
Like this?
[bool]($myObject.PSobject.Properties.name -match "myPropertyNameToTest")
As said in the documentation:
Must: The clause (query) must appear in matching documents.
Should: The clause (query) should appear in the matching document. In a boolean query with no must clauses, one or more should clauses must match a document. The minimum number of should clauses to match can be set using the minimum_should_match parameter.
In other words, results will have to be matched by all the queries present in the must clause ( or match at least one of the should clauses if there is no must clause.
Since you want your results to satisfy all the queries, you should use must.
You can indeed use filters inside a boolean query.
I just want to present a more recent alternative. There is an online tool that generates .gitignore
files based on operating systems, IDEs and programming languages that you might be using.
EDIT Disclaimer: Do not copy this file, copy the file generated by the website instead, they do a good job on keeping it updated. This is just an example.
The file generated for IntelliJ
contains the following
# Created by https://www.gitignore.io/api/intellij
### Intellij ###
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
# User-specific stuff:
.idea/workspace.xml
.idea/tasks.xml
.idea/dictionaries
.idea/vcs.xml
.idea/jsLibraryMappings.xml
# Sensitive or high-churn files:
.idea/dataSources.ids
.idea/dataSources.xml
.idea/dataSources.local.xml
.idea/sqlDataSources.xml
.idea/dynamic.xml
.idea/uiDesigner.xml
# Gradle:
.idea/gradle.xml
.idea/libraries
# Mongo Explorer plugin:
.idea/mongoSettings.xml
## File-based project format:
*.iws
## Plugin-specific files:
# IntelliJ
/out/
# mpeltonen/sbt-idea plugin
.idea_modules/
# JIRA plugin
atlassian-ide-plugin.xml
# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties
### Intellij Patch ###
# Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721
# *.iml
# modules.xml
Just to add another piece of info to this for anyone like me who happens along that just has a single application.
I had my application set up with the main app.module.ts and I had routing with the routing module in it's own folder under the main application. I went through and did some 'cleaning up' since I had a few other things that needed to be organized better. One thing I did was move the routing.module.ts to the root folder; since it was the only file in the folder I figured it didn't need it's own folder.
This worked fine at first but next time I tried to generate a new component (some time later, through the WebStorm IDE) it failed with this message. After reading through this I tried putting the routing module back into a separate folder and it worked again.
So note of warning to others, don't move the routing module into your root folder! I'm sure there are other ways to deal with this too but I'm happy with it in it's own folder for now and using the IDE generator like I was previously.
The code for the confirmation dialogue can be written shorter this way:
$scope.$on('$locationChangeStart', function( event ) {
var answer = confirm("Are you sure you want to leave this page?")
if (!answer) {
event.preventDefault();
}
});
With .split
:
var arr = str.split( /(?<=^(?:.{3})+)(?!$)/ ) // [ 'abc', 'def', 'ghi', 'jkl' ]
and .replace
will be:
var replaced = str.replace( /(?<=^(.{3})+)(?!$)/g, ' || ' ) // 'abc || def || ghi || jkl'
/(?!$)/
is to to stop before end/$/
, without is:
var arr = str.split( /(?<=^(?:.{3})+)/ ) // [ 'abc', 'def', 'ghi', 'jkl' ] // I don't know why is not [ 'abc', 'def', 'ghi', 'jkl' , '' ], comment?
var replaced = str.replace( /(?<=^(.{3})+)/g, ' || ') // 'abc || def || ghi || jkl || '
ignoring group /(?:
...)/
is no need in .replace
but in .split
is adding groups to arr:
var arr = str.split( /(?<=^(.{3})+)(?!$)/ ) // [ 'abc', 'abc', 'def', 'abc', 'ghi', 'abc', 'jkl' ]
I'd start with:
secedit /export /areas USER_RIGHTS /cfg OUTFILE.CFG
Then examine the line for the relevant privilege. However, the problem now is that the accounts are listed as SIDs, not usernames.
Use this XPath expression:
/*/*/X/node()
This selects any node (element, text node, comment or processing instruction) that is a child of any X
element that is a grand-child of the top element of the XML document.
To verify what is selected, here is this XSLT transformation that outputs exactly the selected nodes:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes"/>
<xsl:template match="/">
<xsl:copy-of select="/*/*/X/node()"/>
</xsl:template>
</xsl:stylesheet>
and it produces exactly the wanted, correct result:
First Text Node #1
<y> Y can Have Child Nodes #
<child> deep to it </child>
</y> Second Text Node #2
<z />
Explanation:
As defined in the W3 XPath 1.0 Spec, "child::node()
selects all the children of the context node, whatever their node type." This means that any element, text-node, comment-node and processing-instruction node children are selected by this node-test.
node()
is an abbreviation of child::node()
(because child::
is the primary axis and is used when no axis is explicitly specified).
We can create Linear LayoutParams & use resources.getDimensionPixelSize for dp value.
val mContext = parent.context
val mImageView = AppCompatImageView(mContext)
mImageView.setBackgroundResource(R.drawable.payment_method_selector)
val height = mContext.resources.getDimensionPixelSize(R.dimen.payment_logo_height)
val width = mContext.resources.getDimensionPixelSize(R.dimen.payment_logo_width)
val padding = mContext.resources.getDimensionPixelSize(R.dimen.spacing_small_tiny)
val margin = mContext.resources.getDimensionPixelSize(R.dimen.spacing_small)
mImageView.layoutParams = LinearLayout.LayoutParams(width, height).apply {
setMargins(margin, margin, 0, 0)
}
mImageView.setPadding(padding, padding, padding, padding)
I've found that the jQuery Calendar plugin, for me at least, in general just works better for selecting dates.
When trying to silently install an MSI via PowerShell using this command:
Start-Process $webDeployInstallerFilePath -ArgumentList '/quiet' -Wait
I was getting the error:
The specified executable is not a valid application for this OS platform.
I instead switched to using msiexec.exe
to execute the MSI with this command, and it worked as expected:
$arguments = "/i `"$webDeployInstallerFilePath`" /quiet"
Start-Process msiexec.exe -ArgumentList $arguments -Wait
Hopefully others find this useful.
Tips from 2020:
From Flask 1.0, it defaults to enable multiple threads (source), you don't need to do anything, just upgrade it with:
$ pip install -U flask
If you are using flask run
instead of app.run()
with older versions, you can control the threaded behavior with a command option (--with-threads/--without-threads
):
$ flask run --with-threads
It's same as app.run(threaded=True)
I hope this helps:
import string
alphas = list(string.ascii_letters[:26])
for chr in alphas:
print(chr)
Style the left column with position: fixed
. (You'll presumably want to use top
and left
styles to control where exactly it occurs.)
Extending @Def_Os's answer with an actual demo...
As @Def_Os has already said - using Pandas Datareader makes this task a real fun
In [12]: from pandas_datareader import data
pulling all available historical data for AAPL
starting from 1980-01-01
#In [13]: aapl = data.DataReader('AAPL', 'yahoo', '1980-01-01')
# yahoo api is inconsistent for getting historical data, please use google instead.
In [13]: aapl = data.DataReader('AAPL', 'google', '1980-01-01')
first 5 rows
In [14]: aapl.head()
Out[14]:
Open High Low Close Volume Adj Close
Date
1980-12-12 28.750000 28.875000 28.750 28.750 117258400 0.431358
1980-12-15 27.375001 27.375001 27.250 27.250 43971200 0.408852
1980-12-16 25.375000 25.375000 25.250 25.250 26432000 0.378845
1980-12-17 25.875000 25.999999 25.875 25.875 21610400 0.388222
1980-12-18 26.625000 26.750000 26.625 26.625 18362400 0.399475
last 5 rows
In [15]: aapl.tail()
Out[15]:
Open High Low Close Volume Adj Close
Date
2016-06-07 99.250000 99.870003 98.959999 99.029999 22366400 99.029999
2016-06-08 99.019997 99.559998 98.680000 98.940002 20812700 98.940002
2016-06-09 98.500000 99.989998 98.459999 99.650002 26419600 99.650002
2016-06-10 98.529999 99.349998 98.480003 98.830002 31462100 98.830002
2016-06-13 98.690002 99.120003 97.099998 97.339996 37612900 97.339996
save all data as CSV file
In [16]: aapl.to_csv('d:/temp/aapl_data.csv')
d:/temp/aapl_data.csv - 5 first rows
Date,Open,High,Low,Close,Volume,Adj Close
1980-12-12,28.75,28.875,28.75,28.75,117258400,0.431358
1980-12-15,27.375001,27.375001,27.25,27.25,43971200,0.408852
1980-12-16,25.375,25.375,25.25,25.25,26432000,0.378845
1980-12-17,25.875,25.999999,25.875,25.875,21610400,0.38822199999999996
1980-12-18,26.625,26.75,26.625,26.625,18362400,0.399475
...
This should help.
To sum it up: a generic Pair
class doesn't have any special semantics and you could as well need a Tripplet
class etc. The developers of Java thus didn't include a generic Pair
but suggest to write special classes (which isn't that hard) like Point(x,y)
, Range(start, end)
or Map.Entry(key, value)
.
('0' * 7 + bin(6)[2:])[-8:]
or
right_side = bin(6)[2:]
'0' * ( 8 - len( right_side )) + right_side
We can use the formula method of aggregate
. The variables on the 'rhs' of ~
are the grouping variables while the .
represents all other variables in the 'df1' (from the example, we assume that we need the mean
for all the columns except the grouping), specify the dataset and the function (mean
).
aggregate(.~id1+id2, df1, mean)
Or we can use summarise_each
from dplyr
after grouping (group_by
)
library(dplyr)
df1 %>%
group_by(id1, id2) %>%
summarise_each(funs(mean))
Or using summarise
with across
(dplyr
devel version - ‘0.8.99.9000’
)
df1 %>%
group_by(id1, id2) %>%
summarise(across(starts_with('val'), mean))
Or another option is data.table
. We convert the 'data.frame' to 'data.table' (setDT(df1)
, grouped by 'id1' and 'id2', we loop through the subset of data.table (.SD
) and get the mean
.
library(data.table)
setDT(df1)[, lapply(.SD, mean), by = .(id1, id2)]
df1 <- structure(list(id1 = c("a", "a", "a", "a", "b", "b",
"b", "b"
), id2 = c("x", "x", "y", "y", "x", "y", "x", "y"),
val1 = c(1L,
2L, 3L, 4L, 1L, 4L, 3L, 2L), val2 = c(9L, 4L, 5L, 9L, 7L, 4L,
9L, 8L)), .Names = c("id1", "id2", "val1", "val2"),
class = "data.frame", row.names = c("1",
"2", "3", "4", "5", "6", "7", "8"))
var params = [
'height='+screen.height,
'width='+screen.width,
'fullscreen=yes' // only works in IE, but here for completeness
].join(',');
// and any other options from
// https://developer.mozilla.org/en/DOM/window.open
var popup = window.open('http://www.google.com', 'popup_window', params);
popup.moveTo(0,0);
Please refrain from opening the popup unless the user really wants it, otherwise they will curse you and blacklist your site. ;-)
edit: Oops, as Joren Van Severen points out in a comment, this may not take into account taskbars and window decorations (in a possibly browser-dependent way). Be aware. It seems that ignoring height and width (only param is fullscreen=yes
) seems to work on Chrome and perhaps Firefox too; the original 'fullscreen' functionality has been disabled in Firefox for being obnoxious, but has been replaced with maximization. This directly contradicts information on the same page of https://developer.mozilla.org/en/DOM/window.open which says that window-maximizing is impossible. This 'feature' may or may not be supported depending on the browser.
window.scrollTo(0,1);
this will help you but this javascript is may not work in all browsers
jarsigner can use your pfx file as the keystore for signing your jar. Be sure that your pfx file has the private key and the cert chain when you export it. There is no need to convert to other formats. The trick is to obtain the Alias of your pfx file:
keytool -list -storetype pkcs12 -keystore your_pfx_file -v | grep Alias
Once you have your alias, signing is easy
jarsigner.exe -storetype pkcs12 -keystore pfx_file jar_file "your alias"
The above two commands will prompt you for the password you specified at pfx export. If you want to have your password hang out in clear text use the -storepass switch before the -keystore switch
Once signed, admire your work:
jarsigner.exe -verify -verbose -certs yourjarfile
There is no good solution to your problem, so here is an okey solution ;-)
It keeps your efficiency when assertions are disabled and when assertions are enabled it will raise an assertion error when the hash value is wrong.
I suspect that the D programming language could compute the hash value during compile time, thus removing the need to explicitly write down the hash value.
template <std::size_t h>
struct prehash
{
const your_string_type str;
static const std::size_t hash_value = h;
pre_hash(const your_string_type& s) : str(s)
{
assert(_myhash(s) == hash_value);
}
};
/* ... */
std::size_t h = _myhash(mystring);
static prehash<66452> first_label = "label1";
switch (h) {
case first_label.hash_value:
// ...
;
}
By the way, consider removing the initial underscore from the declaration of _ myhash() (sorry but stackoverflow forces me to insert a space between _ and myhash). A C++ implementation is free to implement macros with names starting with underscore and an uppercase letter (Item 36 of "Exceptional C++ Style" by Herb Sutter), so if you get into the habit of giving things names that start underscore, then a beautiful day could come when you give a symbol a name that starts with underscore and an uppercase letter, where the implementation has defined a macro with the same name.
Go to Behavior > Site Content > All Pages and put your URI into the search box.
I am using Android Studio 3.0 Beta 7. Clean Project, Invalidate caches, restart studio did not work but Updating Kotlin version to 1.1.51 and restart studio solved this issue for me.
If you want to have the power of XPATH combined with the ability to also use CSS at any point you can use parsel
:
>>> from parsel import Selector
>>> sel = Selector(text=u"""<html>
<body>
<h1>Hello, Parsel!</h1>
<ul>
<li><a href="http://example.com">Link 1</a></li>
<li><a href="http://scrapy.org">Link 2</a></li>
</ul
</body>
</html>""")
>>>
>>> sel.css('h1::text').extract_first()
'Hello, Parsel!'
>>> sel.xpath('//h1/text()').extract_first()
'Hello, Parsel!'
In my case I had this referenceError as the order of script calls was wrong. Solved that by changing the order:
<script src="js/index.js"></script>
<script src="js/jquery-1.10.2.js"></script>
to
<script src="js/jquery-1.10.2.js"></script>
<script src="js/index.js"></script>
You can simply do this with a bool:
if int(number) == float(number):
number = int(number)
else:
number = float(number)
The concept of number/length/dimensionality doesn't really make sense for an Object, and needing it suggests you really want an Array to me.
Edit: Pointed out to me that you want an O(1) for this. To the best of my knowledge no such way exists I'm afraid.
Here's a simple lock mechanism, implemented via closure
const createLock = () => {
let lockStatus = false
const release = () => {
lockStatus = false
}
const acuire = () => {
if (lockStatus == true)
return false
lockStatus = true
return true
}
return {
lockStatus: lockStatus,
acuire: acuire,
release: release,
}
}
lock = createLock() // create a lock
lock.acuire() // acuired a lock
if (lock.acuire()){
console.log("Was able to acuire");
} else {
console.log("Was not to acuire"); // This will execute
}
lock.release() // now the lock is released
if(lock.acuire()){
console.log("Was able to acuire"); // This will execute
} else {
console.log("Was not to acuire");
}
lock.release() // Hey don't forget to release
_x000D_
normed_matrix = normalize(input_data, axis=1, norm='l1')
print(normed_matrix)
where input_data is the name of your 2D array
The Data Access Object is basically an object or an interface that provides access to an underlying database or any other persistence storage.
That definition from: http://en.wikipedia.org/wiki/Data_access_object
Check also the sequence diagram here: http://www.oracle.com/technetwork/java/dataaccessobject-138824.html
Maybe a simple example can help you understand the concept:
Let's say we have an entity to represent an employee:
public class Employee {
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
The employee entities will be persisted into a corresponding Employee
table in a database.
A simple DAO interface to handle the database operation required to manipulate an employee entity will be like:
interface EmployeeDAO {
List<Employee> findAll();
List<Employee> findById();
List<Employee> findByName();
boolean insertEmployee(Employee employee);
boolean updateEmployee(Employee employee);
boolean deleteEmployee(Employee employee);
}
Next we have to provide a concrete implementation for that interface to deal with SQL server, and another to deal with flat files, etc.
Assignment in javascript works from right to left. var var1 = var2 = var3 = 1;
.
If the value of any of these variables is 1
after this statement, then logically it must have started from the right, otherwise the value or var1
and var2
would be undefined.
You can think of it as equivalent to var var1 = (var2 = (var3 = 1));
where the inner-most set of parenthesis is evaluated first.
What about one of these?
object.methods.sort
Class.methods.sort
This is a very old, but still very useful thread. I came here recently with the same issue. I suggest protecting the sheet when appropriate and unprotecting it when the filter row (eg Row 1) is selected. My solution doesn't use password protection - I don't need it (its a safeguard, not a security feature). I can't find an event handler that recognizes selection of a filter button - so I gave the instruction to my users to first select the filter cell then click the filter button. Here's what I advocate, (I only change protection if it needs to be changed, that may or may not save time - I don't know, but it "feels" right):
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Const FilterRow = 1
Dim c As Range
Dim NotFilterRow As Boolean
Dim oldstate As Boolean
Dim ws As Worksheet
Set ws = ActiveSheet
oldstate = ws.ProtectContents
NotFilterRow = False
For Each c In Target.Cells
NotFilterRow = c.Row <> FilterRow
If NotFilterRow Then Exit For
Next c
If NotFilterRow <> oldstate Then
If NotFilterRow Then
ws.Protect
Else
ws.Unprotect
End If
End If
Set ws = Nothing
End Sub
As mentioned in other answers Node JS currently doesn't support ES6 imports.
(As of now, read EDIT 2)
Enable ES6 imports in node js provides a solution to this issue. I have tried this and it worked for me.
Run the command:
npm install babel-register babel-preset-env --save-dev
Now you need to create a new file (config.js) and add the following code to it.
require('babel-register')({
presets: [ 'env' ]
})
// Import the rest of our application.
module.exports = require('./your_server_file.js')
Now you can write import statements without getting any errors.
Hope this helps.
EDIT:
You need to run the new file which you created with above code. In my case it was config.js
. So I have to run:
node config.js
EDIT 2:
While experimenting, I found one easy solution to this issue.
Create .babelrc
file in the root of your project.
Add following (and any other babel presets you need, can be added in this file):
{
"presets": ["env"]
}
Install babel-preset-env
using command npm install babel-preset-env --save
, and then install babel-cli
using command npm install babel-cli -g --save
Now, go to the folder where your server or index file exists and run using: babel-node fileName.js
Or you can run using npm start
by adding following code to your package.json
file:
"scripts": {
"start": "babel-node src/index.js"
}
If you're using Node.js:
> var ObjectId = require('mongodb').ObjectId;
> var id = req.params.gonderi_id;
> var o_id = new ObjectId(id);
> db.test.find({_id:o_id})
Edit: corrected to new ObjectId(id), not new ObjectID(id)
.NET Core will install and run on macOS - and just about any other desktop OS.
IDEs are available for the mac, including:
Mono is a good option that I've used in the past. But with Core 3.0 out now, I would go that route.
but an actual alias for a dir is also possible, try
myScripts="~/Files/Scripts/Main"
alias myScripts="cd $myScripts"
This way you have a common naming convention (for each dir/alias pair), and if you need to copy something from the current dir to myScripts, you don't have to think about it.
IHTH
When creating a New Project, under the language of your choice, select Web and then change to .NET Framework 3.5 and you will get the option of creating an ASP.NET WEB Service Application.
$( ".nav li" ).click(function() {
$('.nav li').removeClass('active');
$(this).addClass('active');
});
check this out.
Just to add a non-regex solution:
'(' + $myString.Split('()')[1] + ')'
This splits the string at the parentheses and takes the string from the array with the program name in it.
If you don't need the parentheses, just use:
$myString.Split('()')[1]
Use java.util.Calendar
if you have extensive date related processing.
Date has before()
, after()
methods. you could use them as well.
It's pandas
label-based selection, as explained here: https://pandas.pydata.org/pandas-docs/stable/indexing.html#selection-by-label
The boolean array is basically a selection method using a mask.
There are many ways to check the size, but as a developer we dont have much access to query meta tables, I find this solution very easy (Note: if you are getting error message ORA-01653 ‘The ORA-01653 error is caused because you need to add space to a tablespace.’)
--Size of All Table Space
--1. Used Space
SELECT TABLESPACE_NAME,TO_CHAR(SUM(NVL(BYTES,0))/1024/1024/1024, '99,999,990.99') AS "USED SPACE(IN GB)" FROM USER_SEGMENTS GROUP BY TABLESPACE_NAME
--2. Free Space
SELECT TABLESPACE_NAME,TO_CHAR(SUM(NVL(BYTES,0))/1024/1024/1024, '99,999,990.99') AS "FREE SPACE(IN GB)" FROM USER_FREE_SPACE GROUP BY TABLESPACE_NAME
--3. Both Free & Used
SELECT USED.TABLESPACE_NAME, USED.USED_BYTES AS "USED SPACE(IN GB)", FREE.FREE_BYTES AS "FREE SPACE(IN GB)"
FROM
(SELECT TABLESPACE_NAME,TO_CHAR(SUM(NVL(BYTES,0))/1024/1024/1024, '99,999,990.99') AS USED_BYTES FROM USER_SEGMENTS GROUP BY TABLESPACE_NAME) USED
INNER JOIN
(SELECT TABLESPACE_NAME,TO_CHAR(SUM(NVL(BYTES,0))/1024/1024/1024, '99,999,990.99') AS FREE_BYTES FROM USER_FREE_SPACE GROUP BY TABLESPACE_NAME) FREE
ON (USED.TABLESPACE_NAME = FREE.TABLESPACE_NAME);
Thanks
To avoid many if-else structures, let JavaScript do the trick automatically:
<select name="name" id="name">
<option value="a">a</option>
<option value="b">b</option>
</select>
<script type="text/javascript">
document.getElementById('name').value = "<?php echo $_GET['name'];?>";
</script>
<select name="location" id="location">
<option value="x">x</option>
<option value="y">y</option>
</select>
<script type="text/javascript">
document.getElementById('location').value = "<?php echo $_GET['location'];?>";
</script>
I know it's an old posting, but nowadays the easier/quicker option is to use the enhanced printing services offered by the WPF framework (usable by non-WPF apps).
http://msdn.microsoft.com/en-us/library/System.Printing(v=vs.110).aspx
An example to retrieve the status of the printer queue and first job..
var queue = new LocalPrintServer().GetPrintQueue("Printer Name");
var queueStatus = queue.QueueStatus;
var jobStatus = queue.GetPrintJobInfoCollection().FirstOrDefault().JobStatus
From my looking you give a null value to a textbox and return in a ToString()
as it is a static method. You can replace it with Convert.ToString()
that can enable null value.
According to w3 post,
200 OK
The request has succeeded. The information returned with the response is dependent on the method used in the request
202 Accepted
The request has been accepted for processing, but the processing has not been completed.
204 No Content
The server has fulfilled the request but does not need to return an entity-body, and might want to return updated metainformation.
400 Bad Request
The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications
401 Unauthorized
The request requires user authentication. The response MUST include a WWW-Authenticate header field
404 Not Found
The server has not found anything matching the Request-URI. No indication is given of whether the condition is temporary or permanent
PEP 8 advises the first form for readability. You can find it here.
Function names should be lowercase, with words separated by underscores as necessary to improve readability.
You could try
moment().add(1, 'M').subtract(1, 'day').format('DD-MM-YYYY')
Since I wrote the MSDN article you are referring to, I guess I have to answer this one.
First, I anticipated this question and that's why I wrote a blog post that shows a more or less real use case for ExpandoObject: Dynamic in C# 4.0: Introducing the ExpandoObject.
Shortly, ExpandoObject can help you create complex hierarchical objects. For example, imagine that you have a dictionary within a dictionary:
Dictionary<String, object> dict = new Dictionary<string, object>();
Dictionary<String, object> address = new Dictionary<string,object>();
dict["Address"] = address;
address["State"] = "WA";
Console.WriteLine(((Dictionary<string,object>)dict["Address"])["State"]);
The deeper is the hierarchy, the uglier is the code. With ExpandoObject it stays elegant and readable.
dynamic expando = new ExpandoObject();
expando.Address = new ExpandoObject();
expando.Address.State = "WA";
Console.WriteLine(expando.Address.State);
Second, as it was already pointed out, ExpandoObject implements INotifyPropertyChanged interface which gives you more control over properties than a dictionary.
Finally, you can add events to ExpandoObject like here:
class Program
{
static void Main(string[] args)
{
dynamic d = new ExpandoObject();
// Initialize the event to null (meaning no handlers)
d.MyEvent = null;
// Add some handlers
d.MyEvent += new EventHandler(OnMyEvent);
d.MyEvent += new EventHandler(OnMyEvent2);
// Fire the event
EventHandler e = d.MyEvent;
e?.Invoke(d, new EventArgs());
}
static void OnMyEvent(object sender, EventArgs e)
{
Console.WriteLine("OnMyEvent fired by: {0}", sender);
}
static void OnMyEvent2(object sender, EventArgs e)
{
Console.WriteLine("OnMyEvent2 fired by: {0}", sender);
}
}
Also, keep in mind that nothing is preventing you from accepting event arguments in a dynamic way. In other words, instead of using EventHandler
, you can use EventHandler<dynamic>
which would cause the second argument of the handler to be dynamic
.
This code help me in Attachment sending....
$mail->AddAttachment($_FILES['file']['tmp_name'], $_FILES['file']['name']);
Replace your AddAttachment(...) Code with above code
Using the stat
to figure out the last modification date of the file, date
to figure out the current time and a liberal use of bashisms, one can do the test that you want based on the file's last modification time1.
if [ "$(( $(date +"%s") - $(stat -c "%Y" $somefile) ))" -gt "7200" ]; then
echo "$somefile is older then 2 hours"
fi
While the code is a bit less readable then the find
approach, I think its a better approach then running find
to look at a file you already "found". Also, date manipulation is fun ;-)
%Z
instead of %Y
below to get "change time" which may be what you want.[Update]
For mac users, use stat -f "%m" $somefile
instead of the Linux specific syntax above
Use setInterval
:
$(function(){
setInterval(oneSecondFunction, 1000);
});
function oneSecondFunction() {
// stuff you want to do every second
}
Here's an article on the difference between setTimeout
and setInterval
. Both will provide the functionality you need, they just require different implementations.
Necromancing.
I assume when somebody lands here, he needs a foreign key to column in a table that contains non-unique keys.
The problem is, that if you have that problem, the database-schema is denormalized.
You're for example keeping rooms in a table, with a room-uid primary key, a DateFrom and a DateTo field, and another uid, here RM_ApertureID to keep track of the same room, and a soft-delete field, like RM_Status, where 99 means 'deleted', and <> 99 means 'active'.
So when you create the first room, you insert RM_UID and RM_ApertureID as the same value as RM_UID. Then, when you terminate the room to a date, and re-establish it with a new date range, RM_UID is newid(), and the RM_ApertureID from the previous entry becomes the new RM_ApertureID.
So, if that's the case, RM_ApertureID is a non-unique field, and so you can't set a foreign-key in another table.
And there is no way to set a foreign key to a non-unique column/index, e.g. in T_ZO_REM_AP_Raum_Reinigung (WHERE RM_UID is actually RM_ApertureID).
But to prohibit invalid values, you need to set a foreign key, otherwise, data-garbage is the result sooner rather than later...
Now what you can do in this case (short of rewritting the entire application) is inserting a CHECK-constraint, with a scalar function checking the presence of the key:
IF EXISTS (SELECT * FROM sys.check_constraints WHERE object_id = OBJECT_ID(N'[dbo].[Check_RM_ApertureIDisValid_T_ZO_REM_AP_Raum_Reinigung]') AND parent_object_id = OBJECT_ID(N'[dbo].[T_ZO_REM_AP_Raum_Reinigung]'))
ALTER TABLE dbo.T_ZO_REM_AP_Raum_Reinigung DROP CONSTRAINT [Check_RM_ApertureIDisValid_T_ZO_REM_AP_Raum_Reinigung]
GO
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fu_Constaint_ValidRmApertureId]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[fu_Constaint_ValidRmApertureId]
GO
CREATE FUNCTION [dbo].[fu_Constaint_ValidRmApertureId](
@in_RM_ApertureID uniqueidentifier
,@in_DatumVon AS datetime
,@in_DatumBis AS datetime
,@in_Status AS integer
)
RETURNS bit
AS
BEGIN
DECLARE @bNoCheckForThisCustomer AS bit
DECLARE @bIsInvalidValue AS bit
SET @bNoCheckForThisCustomer = 'false'
SET @bIsInvalidValue = 'false'
IF @in_Status = 99
RETURN 'false'
IF @in_DatumVon > @in_DatumBis
BEGIN
RETURN 'true'
END
IF @bNoCheckForThisCustomer = 'true'
RETURN @bIsInvalidValue
IF NOT EXISTS
(
SELECT
T_Raum.RM_UID
,T_Raum.RM_Status
,T_Raum.RM_DatumVon
,T_Raum.RM_DatumBis
,T_Raum.RM_ApertureID
FROM T_Raum
WHERE (1=1)
AND T_Raum.RM_ApertureID = @in_RM_ApertureID
AND @in_DatumVon >= T_Raum.RM_DatumVon
AND @in_DatumBis <= T_Raum.RM_DatumBis
AND T_Raum.RM_Status <> 99
)
SET @bIsInvalidValue = 'true' -- IF !
RETURN @bIsInvalidValue
END
GO
IF EXISTS (SELECT * FROM sys.check_constraints WHERE object_id = OBJECT_ID(N'[dbo].[Check_RM_ApertureIDisValid_T_ZO_REM_AP_Raum_Reinigung]') AND parent_object_id = OBJECT_ID(N'[dbo].[T_ZO_REM_AP_Raum_Reinigung]'))
ALTER TABLE dbo.T_ZO_REM_AP_Raum_Reinigung DROP CONSTRAINT [Check_RM_ApertureIDisValid_T_ZO_REM_AP_Raum_Reinigung]
GO
-- ALTER TABLE dbo.T_AP_Kontakte WITH CHECK ADD CONSTRAINT [Check_RM_ApertureIDisValid_T_ZO_REM_AP_Raum_Reinigung]
ALTER TABLE dbo.T_ZO_REM_AP_Raum_Reinigung WITH NOCHECK ADD CONSTRAINT [Check_RM_ApertureIDisValid_T_ZO_REM_AP_Raum_Reinigung]
CHECK
(
NOT
(
dbo.fu_Constaint_ValidRmApertureId(ZO_RMREM_RM_UID, ZO_RMREM_GueltigVon, ZO_RMREM_GueltigBis, ZO_RMREM_Status) = 1
)
)
GO
IF EXISTS (SELECT * FROM sys.check_constraints WHERE object_id = OBJECT_ID(N'[dbo].[Check_RM_ApertureIDisValid_T_ZO_REM_AP_Raum_Reinigung]') AND parent_object_id = OBJECT_ID(N'[dbo].[T_ZO_REM_AP_Raum_Reinigung]'))
ALTER TABLE dbo.T_ZO_REM_AP_Raum_Reinigung CHECK CONSTRAINT [Check_RM_ApertureIDisValid_T_ZO_REM_AP_Raum_Reinigung]
GO
For me I had to uncomment these lines in php.ini:
extension=php_openssl.dll
extension_dir = "ext"
"ext" is applicable if php_openssl.dll is located in the "ext" folder.
Note: I had to do this for two of my php.ini files otherwise it would not work. One located in the vs.php installation folder, and the other on on the PHP folder
C:\Program Files (x86)\Jcx.Software\VS.Php\2013\Php 5.6
C:\Program Files (x86)\PHP\v5.6
Python 2.7 and 3.2 added the collections.Counter
class, which is a dictionary subclass that maps elements to the number of occurrences of the element. This can be used as a multiset. You can do something like this:
from collections import Counter
a = Counter([0, 1, 2, 1, 0])
b = Counter([0, 1, 1])
c = a - b # ignores items in b missing in a
print(list(c.elements())) # -> [0, 2]
As well, if you want to check that every element in b
is in a
:
# a[key] returns 0 if key not in a, instead of raising an exception
assert all(a[key] >= b[key] for key in b)
But since you are stuck with 2.5, you could try importing it and define your own version if that fails. That way you will be sure to get the latest version if it is available, and fall back to a working version if not. You will also benefit from speed improvements if if gets converted to a C implementation in the future.
try:
from collections import Counter
except ImportError:
class Counter(dict):
...
You can find the current Python source here.
Yes. In Ruby the not equal to operator is:
!=
You can get a full list of ruby operators here: https://www.tutorialspoint.com/ruby/ruby_operators.htm.
I would assume it's possible to place a proxy between the DB and your app then observe the communication. I'm not familiar with what software you would use to do this.
Just to add a bit of extra info over the right solution. Be aware that you'll need this class org.apache.catalina.filters.CorsFilter. So in order to have it, if your tomcat is not 7.0.41 or higher, download 'tomcat-catalina.7.0.41.jar' or higher ( you can do it from http://mvnrepository.com/artifact/org.apache.tomcat/tomcat-catalina ) and put it in the 'lib' folder inside Tomcat installation folders. I actually used 7.0.42 Hope it helps!
Nope, it is more complicated than just calling a method, if you want to transparently add it into the user's calendar.
You've got a couple of choices;
Calling the intent to add an event on the calendar
This will pop up the Calendar application and let the user add the event. You can pass some parameters to prepopulate fields:
Calendar cal = Calendar.getInstance();
Intent intent = new Intent(Intent.ACTION_EDIT);
intent.setType("vnd.android.cursor.item/event");
intent.putExtra("beginTime", cal.getTimeInMillis());
intent.putExtra("allDay", false);
intent.putExtra("rrule", "FREQ=DAILY");
intent.putExtra("endTime", cal.getTimeInMillis()+60*60*1000);
intent.putExtra("title", "A Test Event from android app");
startActivity(intent);
Or the more complicated one:
Get a reference to the calendar with this method
(It is highly recommended not to use this method, because it could break on newer Android versions):
private String getCalendarUriBase(Activity act) {
String calendarUriBase = null;
Uri calendars = Uri.parse("content://calendar/calendars");
Cursor managedCursor = null;
try {
managedCursor = act.managedQuery(calendars, null, null, null, null);
} catch (Exception e) {
}
if (managedCursor != null) {
calendarUriBase = "content://calendar/";
} else {
calendars = Uri.parse("content://com.android.calendar/calendars");
try {
managedCursor = act.managedQuery(calendars, null, null, null, null);
} catch (Exception e) {
}
if (managedCursor != null) {
calendarUriBase = "content://com.android.calendar/";
}
}
return calendarUriBase;
}
and add an event and a reminder this way:
// get calendar
Calendar cal = Calendar.getInstance();
Uri EVENTS_URI = Uri.parse(getCalendarUriBase(this) + "events");
ContentResolver cr = getContentResolver();
// event insert
ContentValues values = new ContentValues();
values.put("calendar_id", 1);
values.put("title", "Reminder Title");
values.put("allDay", 0);
values.put("dtstart", cal.getTimeInMillis() + 11*60*1000); // event starts at 11 minutes from now
values.put("dtend", cal.getTimeInMillis()+60*60*1000); // ends 60 minutes from now
values.put("description", "Reminder description");
values.put("visibility", 0);
values.put("hasAlarm", 1);
Uri event = cr.insert(EVENTS_URI, values);
// reminder insert
Uri REMINDERS_URI = Uri.parse(getCalendarUriBase(this) + "reminders");
values = new ContentValues();
values.put( "event_id", Long.parseLong(event.getLastPathSegment()));
values.put( "method", 1 );
values.put( "minutes", 10 );
cr.insert( REMINDERS_URI, values );
You'll also need to add these permissions to your manifest for this method:
<uses-permission android:name="android.permission.READ_CALENDAR" />
<uses-permission android:name="android.permission.WRITE_CALENDAR" />
Update: ICS Issues
The above examples use the undocumented Calendar APIs, new public Calendar APIs have been released for ICS, so for this reason, to target new android versions you should use CalendarContract.
More infos about this can be found at this blog post.
Take a look at this page on implementing graphs in python.
You could also take a look at pygraphlib on sourceforge.
Don't fart around with inserting spaces. For one, older versions of IE won't know what you're talking about. Besides that, though, there are cleaner ways in general.
For colorless indents, use the text-indent
property.
p { text-indent: 1em; }
Edit:
If you want the space to be colored, you might consider adding a thick left border to the first letter. (I'd almost-but-not-quite say "instead", because the indent can be an issue if you use both. But it feels dirty to me to rely solely on the border to indent.) You can specify how far away, and how wide, the color is using the first letter's left margin/padding/border width.
p:first-letter { border-left: 1em solid red; }
As other users said, cat() is probably the best option.
@krlmlr suggested using sprintf() and it's currently the third ranked answer. sprintf() is not a good idea. From R documentation:
The format string is passed down the OS's sprintf function, and incorrect formats can cause the latter to crash the R process.
There is no good reason to use sprintf() over cat or other options.
Your Android already identifies with a VID/PID when plugged into a host. It already has an interface for Mass Storage. You would need to hack the driver at a low level to support a 2nd interface for 03:01 HID. Then it would just be a question of pushing scancodes to the modified driver. This wouldn't be simple, but it would be a neat hack. One use would be for typing long random passwords for logins.
Here's a stdlib solution that supports a variable utc offset in the input time string:
>>> from email.utils import parsedate_tz, mktime_tz
>>> from datetime import datetime, timedelta
>>> timestamp = mktime_tz(parsedate_tz('Tue May 08 15:14:45 +0800 2012'))
>>> utc_time = datetime(1970, 1, 1) + timedelta(seconds=timestamp)
>>> utc_time
datetime.datetime(2012, 5, 8, 7, 14, 45)
Try disabling Just My Code (JMC).
By default the debugger tries to restrict the view of the world to code that is only contained within your solution. This is really heplful at times but when you want to debug code which is not in your solution (as is your situation) you need to disable JMC in order to see it. Otherwise the code will be treated as external and largely hidden from your view.
EDIT
When you're broken in your code try the following.
Just a note: for Anaconda install packages command:
Yes, via extensions. Try Bookmarks extension on marketplace.visualstudio.com
Hit Ctrl+Shift+P and type the install extensions
and press enter, then type Bookmark
and press enter.
Next you may wish to customize what keys are used to make a bookmark and move to it. For that see this question.
Try installing these packages.
sudo apt-get install build-essential autoconf libtool pkg-config python-opengl python-pil python-pyrex python-pyside.qtopengl idle-python2.7 qt4-dev-tools qt4-designer libqtgui4 libqtcore4 libqt4-xml libqt4-test libqt4-script libqt4-network libqt4-dbus python-qt4 python-qt4-gl libgle3 python-dev libssl-dev
sudo easy_install greenlet
sudo easy_install gevent
There is a easy way to do it.
NSArray *myArray = @[@"5",@"4",@"3",@"2",@"1"];
NSMutableArray *myNewArray = [[NSMutableArray alloc] init]; //this object is going to be your new array with inverse order.
for(int i=0; i<[myNewArray count]; i++){
[myNewArray insertObject:[myNewArray objectAtIndex:i] atIndex:0];
}
//other way to do it
for(NSString *eachValue in myArray){
[myNewArray insertObject:eachValue atIndex:0];
}
//in both cases your new array will look like this
NSLog(@"myNewArray: %@", myNewArray);
//[@"1",@"2",@"3",@"4",@"5"]
I hope this helps.
the problem might be the wname, try using one of those shown in the link above, i quote:
Optional. String that specifies the name of the window. This name is used as the value for the TARGET attribute on a form or an anchor element.
- _blank The sURL is loaded into a new, unnamed window.
- _media The url is loaded in the Media Bar in Microsoft Internet Explorer 6. Microsoft Windows XP Service Pack 2 (SP2) and later. This feature is no longer supported. By default the url is loaded into a new browser window or tab.
- _parent The sURL is loaded into the current frame's parent. If the frame has no parent, this value acts as the value _self.
- _search Disabled in Windows Internet Explorer 7, see Security and Compatibility in Internet Explorer 7 for details. Otherwise, the sURL is opened in the browser's search pane in Internet Explorer 5 or later.
- _self The current document is replaced with the specified sURL.
- _top sURL replaces any framesets that may be loaded. If there are no framesets defined, this value acts as the value _self.
if using another wname, window.open won't execute...
If the collection size is small you could go with the solution provided by rich.okelly. However, a large collection means that the generation of the dictionary may be noticeably slower than just searching the keys collection.
Also, if your usage scenario is searching for keys in different points in time, where the NameValueCollection may have been modified, generating the dictionary each time may, again, be slower than just searching the keys collection.
None of the examples above create 8-bit (8bpp) bitmap images. Some software, such as image processing, only supports 8bpp. Unfortunately the MS .NET libraries do not have a solution. The PixelFormat.Format8bppIndexed format looks promising but after a lot of attempts I couldn't get it working.
To create a true 8-bit bitmap file you need to create the proper headers. Ultimately I found the Grayscale library solution for creating 8-bit bitmap (BMP) files. The code is very simple:
Image image = Image.FromFile("c:/path/to/image.jpg");
GrayBMP_File.CreateGrayBitmapFile(image, "c:/path/to/8bpp/image.bmp");
The code for this project is far from pretty but it works, with one little simple-to-fix problem. The author hard-coded the image resolution to 10x10. Image processing programs do not like this. The fix is open GrayBMP_File.cs (yeah, funky file naming, I know) and replace lines 50 and 51 with the code below. The example sets the resolution to 200x200 but you should change it to the proper number.
int resX = 200;
int resY = 200;
// horizontal resolution
Copy_to_Index(DIB_header, BitConverter.GetBytes(resX * 100), 24);
// vertical resolution
Copy_to_Index(DIB_header, BitConverter.GetBytes(resY * 100), 28);
Edit: Whoops, didn't check your question tags before answering.
Check that you can actually connect to DB (have the driver placed? tested the conn when creating it?).
If so, try runnung those queries with F5
If you use Mercurial, you can use the built in HTTP server. In the folder you wish to serve up:
hg serve
From the docs:
export the repository via HTTP
Start a local HTTP repository browser and pull server.
By default, the server logs accesses to stdout and errors to
stderr. Use the "-A" and "-E" options to log to files.
options:
-A --accesslog name of access log file to write to
-d --daemon run server in background
--daemon-pipefds used internally by daemon mode
-E --errorlog name of error log file to write to
-p --port port to listen on (default: 8000)
-a --address address to listen on (default: all interfaces)
--prefix prefix path to serve from (default: server root)
-n --name name to show in web pages (default: working dir)
--webdir-conf name of the webdir config file (serve more than one repo)
--pid-file name of file to write process ID to
--stdio for remote clients
-t --templates web templates to use
--style template style to use
-6 --ipv6 use IPv6 in addition to IPv4
--certificate SSL certificate file
use "hg -v help serve" to show global options
Saish's answer using REGEXP_LIKE
is the right idea but does not support floating numbers. This one will ...
Return values that are numeric
SELECT foo
FROM bar
WHERE REGEXP_LIKE (foo,'^-?\d+(\.\d+)?$');
Return values not numeric
SELECT foo
FROM bar
WHERE NOT REGEXP_LIKE (foo,'^-?\d+(\.\d+)?$');
You can test your regular expressions themselves till your heart is content at http://regexpal.com/ (but make sure you select the checkbox match at line breaks for this one).
Just to help those in a similar situation to myself...
This can be caused when a dependent library has accidentally bundled an old version of slf4j. In my case, it was tika-0.8. See https://issues.apache.org/jira/browse/TIKA-556
The workaround is exclude the component and then manually depends on the correct, or patched version.
EG.
<dependency>
<groupId>org.apache.tika</groupId>
<artifactId>tika-parsers</artifactId>
<version>0.8</version>
<exclusions>
<exclusion>
<!-- NOTE: Version 4.2 has bundled slf4j -->
<groupId>edu.ucar</groupId>
<artifactId>netcdf</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<!-- Patched version 4.2-min does not bundle slf4j -->
<groupId>edu.ucar</groupId>
<artifactId>netcdf</artifactId>
<version>4.2-min</version>
</dependency>
With this command:
dpkg -s mysql-server | grep Status
Following with Oleg answer, if you want to find ALL objects in a List filtered by a property, you could do something like:
//Search into a generic list ALL items with a generic property
public final class SearchTools {
public static <T> List<T> findByProperty(Collection<T> col, Predicate<T> filter) {
List<T> filteredList = (List<T>) col.stream().filter(filter).collect(Collectors.toList());
return filteredList;
}
//Search in the list "listItems" ALL items of type "Item" with the specific property "iD_item=itemID"
public static final class ItemTools {
public static List<Item> findByItemID(Collection<Item> listItems, String itemID) {
return SearchTools.findByProperty(listItems, item -> itemID.equals(item.getiD_Item()));
}
}
}
and similarly if you want to filter ALL items in a HashMap with a certain Property
//Search into a MAP ALL items with a given property
public final class SearchTools {
public static <T> HashMap<String,T> filterByProperty(HashMap<String,T> completeMap, Predicate<? super Map.Entry<String,T>> filter) {
HashMap<String,T> filteredList = (HashMap<String,T>) completeMap.entrySet().stream()
.filter(filter)
.collect(Collectors.toMap(map -> map.getKey(), map -> map.getValue()));
return filteredList;
}
//Search into the MAP ALL items with specific properties
public static final class ItemTools {
public static HashMap<String,Item> filterByParentID(HashMap<String,Item> mapItems, String parentID) {
return SearchTools.filterByProperty(mapItems, mapItem -> parentID.equals(mapItem.getValue().getiD_Parent()));
}
public static HashMap<String,Item> filterBySciName(HashMap<String,Item> mapItems, String sciName) {
return SearchTools.filterByProperty(mapItems, mapItem -> sciName.equals(mapItem.getValue().getSciName()));
}
}
For litespeed servers with lsphp*.* package.
Use following command to find out default set memory limit for PHP applications.
php -r "echo ini_get('memory_limit').PHP_EOL;"
To locate active php.ini file from CLI
php -i | grep php.ini
Example:
/usr/local/lsws/lsphp73/etc/php/7.3/litespeed/php.ini
To change php.ini default value to custom:
php_memory_limit=1024M #or what ever you want it set to
sed -i 's/memory_limit = .*/memory_limit = '${php_memory_limit}'/' /usr/local/lsws/lsphp73/etc/php/7.3/litespeed/php.ini
Dont forget to restart lsws with: systemctl restart lsws
If, like me, you are trying to use GETDATE()
within an expression and have the seemingly unreasonable requirement (SSIS/SSDT seems very much a work in progress to me, and not a polished offering) of wanting that date to get inserted into SQL Server as a valid date (type = datetime
), then I found this expression to work:
@[User::someVar] = (DT_WSTR,4)YEAR(GETDATE()) + "-" + RIGHT("0" + (DT_WSTR,2)MONTH(GETDATE()), 2) + "-" + RIGHT("0" + (DT_WSTR,2)DAY( GETDATE()), 2) + " " + RIGHT("0" + (DT_WSTR,2)DATEPART("hh", GETDATE()), 2) + ":" + RIGHT("0" + (DT_WSTR,2)DATEPART("mi", GETDATE()), 2) + ":" + RIGHT("0" + (DT_WSTR,2)DATEPART("ss", GETDATE()), 2)
I found this code snippet HERE
Archive process (using Xcode 8.3.2)
Note : If you are using creating IPA using drag-and-drop process using iTunes Mac app then this is no longer applicable for iTunes 12.7 since there is no built-in App store in iTunes 12.7.
‘Generic iOS Device
’ on device list in Xcodecmd + shift + k
as shortcut)Product
-> Archive
your projectOnce archive is succeeded this will open a window with archived project
You can validate your archive by pressing Validate
(optional step but recommended)
Now press on Export
button
Next
button.list of team for provisioning
. Select accordingly and press on ‘Choose
’ button.Export one app for all compatible devices
(recommended). If you want IPA for specific device then select the device variant from list and press on ‘Next
’ button.Summary
’ and then press on ‘Next
’ buttonexport the IPA as [App Name - Date Time]
and then press on ‘Done
’.Here is working solution:
Output:
public class XmlTest {
private static final Logger log = LoggerFactory.getLogger(XmlTest.class);
@Test
public void createDefaultBook() throws JAXBException {
JAXBContext jaxbContext = JAXBContext.newInstance(Book.class);
Marshaller marshaller = jaxbContext.createMarshaller();
StringWriter writer = new StringWriter();
marshaller.marshal(new Book(), writer);
log.debug("Book xml:\n {}", writer.toString());
}
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "book")
public static class Book {
@XmlElementRef(name = "price")
private Price price = new Price();
}
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "price")
public static class Price {
@XmlAttribute(name = "drawable")
private Boolean drawable = true; //you may want to set default value here
@XmlValue
private int priceValue = 1234;
public Boolean getDrawable() {
return drawable;
}
public void setDrawable(Boolean drawable) {
this.drawable = drawable;
}
public int getPriceValue() {
return priceValue;
}
public void setPriceValue(int priceValue) {
this.priceValue = priceValue;
}
}
}
Output:
22:00:18.471 [main] DEBUG com.grebski.stack.XmlTest - Book xml:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<book>
<price drawable="true">1234</price>
</book>
I came up with this similar situation and I resolved it quiet easily.Here is what I did. Assuming you already have the value in array at your aspx.cs
page.
1)Put a hidden field in your aspx page and us the hidden field ID to store the array value.
HiddenField2.Value = string.Join(",", myarray);
2)Now that the hidden field has the value stored, just separated by commas. Use this hidden field in JavaScript like this. Simply create an array in JavaScript and then store the value in that array by removing the commas.
var hiddenfield2 = new Array();
hiddenfield2=document.getElementById('<%=HiddenField2.ClientID%>').value.split(',');
This should solve your problem.
If you are creating a new table, you can use the inline shortcut:
def change
create_table :posts do |t|
t.string :title, null: false, index: { unique: true }
t.timestamps
end
end
Providing that you have LINQ available and don't care too much about performance, the easiest thing is the following:
var arraysAreEqual = Enumerable.SequenceEqual(a1, a2);
In fact, it's probably worth checking with Reflector or ILSpy what the SequenceEqual
methods actually does, since it may well optimise for the special case of array values anyway!
To show result till yesterday
WHERE DATE(date_time) < CURDATE()
To show results of 10 days
WHERE date_time < NOW() - INTERVAL 10 DAY
To show results before 10 days
WHERE DATE(date_time) < DATE(NOW() - INTERVAL 10 DAY)
These will work for you
You can find dates like this
SELECT DATE(NOW() - INTERVAL 11 DAY)
function remove_script_tags($html){
$dom = new DOMDocument();
$dom->loadHTML($html);
$script = $dom->getElementsByTagName('script');
$remove = [];
foreach($script as $item){
$remove[] = $item;
}
foreach ($remove as $item){
$item->parentNode->removeChild($item);
}
$html = $dom->saveHTML();
$html = preg_replace('/<!DOCTYPE.*?<html>.*?<body><p>/ims', '', $html);
$html = str_replace('</p></body></html>', '', $html);
return $html;
}
Dejan's answer was good, but saveHTML() adds unnecessary doctype and body tags, this should get rid of it. See https://3v4l.org/82FNP
Check Base64 or normal string
public bool IsBase64Encoded(String str)
{
try
{
// If no exception is caught, then it is possibly a base64 encoded string
byte[] data = Convert.FromBase64String(str);
// The part that checks if the string was properly padded to the
// correct length was borrowed from d@anish's solution
return (str.Replace(" ","").Length % 4 == 0);
}
catch
{
// If exception is caught, then it is not a base64 encoded string
return false;
}
}
i like this version:
import java.awt.Dimension;
import java.awt.GraphicsConfiguration;
import java.awt.Toolkit;
import javax.swing.JFrame;
public class Test
{
public static void main(String [] args)
{
final JFrame frame = new JFrame();
final GraphicsConfiguration config = frame.getGraphicsConfiguration();
final int left = Toolkit.getDefaultToolkit().getScreenInsets(config).left;
final int right = Toolkit.getDefaultToolkit().getScreenInsets(config).right;
final int top = Toolkit.getDefaultToolkit().getScreenInsets(config).top;
final int bottom = Toolkit.getDefaultToolkit().getScreenInsets(config).bottom;
final Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
final int width = screenSize.width - left - right;
final int height = screenSize.height - top - bottom;
frame.setResizable(false);
frame.setSize(width,height);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
$('#test').click(function() {_x000D_
var startDate = moment("01.01.2019", "DD.MM.YYYY");_x000D_
var endDate = moment("01.02.2019", "DD.MM.YYYY");_x000D_
_x000D_
var result = 'Diff: ' + endDate.diff(startDate, 'days');_x000D_
_x000D_
$('#result').html(result);_x000D_
});
_x000D_
#test {_x000D_
width: 100px;_x000D_
height: 100px;_x000D_
background: #ffb;_x000D_
padding: 10px;_x000D_
border: 2px solid #999;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.12.0/moment.js"></script>_x000D_
_x000D_
<div id='test'>Click Me!!!</div>_x000D_
<div id='result'></div>
_x000D_
// This is the exact code for search facility in datagridview.
private void buttonSearch_Click(object sender, EventArgs e)
{
string searchValue=textBoxSearch.Text;
int rowIndex = 1; //this one is depending on the position of cell or column
//string first_row_data=dataGridView1.Rows[0].Cells[0].Value.ToString() ;
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
try
{
bool valueResulet = true;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (row.Cells[rowIndex].Value.ToString().Equals(searchValue))
{
rowIndex = row.Index;
dataGridView1.Rows[rowIndex].Selected = true;
rowIndex++;
valueResulet = false;
}
}
if (valueResulet != false)
{
MessageBox.Show("Record is not avalable for this Name"+textBoxSearch.Text,"Not Found");
return;
}
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
}
My issue was not sending the response back, so it was hanging. If you are using express make sure that res.send(data), res.json(data) or whatever the api method you wanna use is executed for the route you are testing.
You need to use Arrow function ()=>
ES6 feature to preserve this
context within setTimeout
.
// var that = this; // no need of this line
this.messageSuccess = true;
setTimeout(()=>{ //<<<---using ()=> syntax
this.messageSuccess = false;
}, 3000);
This doesn't have anything to do with jQuery. You can use the JavaScript replace
function for this:
var str = "data-123";
str = str.replace("data-", "");
You can also pass a regex to this function. In the following example, it would replace everything except numerics:
str = str.replace(/[^0-9\.]+/g, "");
I have done exactly this with an ICustomTypeDescriptor interface and a Dictionary.
Implementing ICustomTypeDescriptor for dynamic properties:
I have recently had a requirement to bind a grid view to a record object that could have any number of properties that can be added and removed at runtime. This was to allow a user to add a new column to a result set to enter an additional set of data.
This can be achieved by having each data 'row' as a dictionary with the key being the property name and the value being a string or a class that can store the value of the property for the specified row. Of course having a List of Dictionary objects will not be able to be bound to a grid. This is where the ICustomTypeDescriptor comes in.
By creating a wrapper class for the Dictionary and making it adhere to the ICustomTypeDescriptor interface the behaviour for returning properties for an object can be overridden.
Take a look at the implementation of the data 'row' class below:
/// <summary>
/// Class to manage test result row data functions
/// </summary>
public class TestResultRowWrapper : Dictionary<string, TestResultValue>, ICustomTypeDescriptor
{
//- METHODS -----------------------------------------------------------------------------------------------------------------
#region Methods
/// <summary>
/// Gets the Attributes for the object
/// </summary>
AttributeCollection ICustomTypeDescriptor.GetAttributes()
{
return new AttributeCollection(null);
}
/// <summary>
/// Gets the Class name
/// </summary>
string ICustomTypeDescriptor.GetClassName()
{
return null;
}
/// <summary>
/// Gets the component Name
/// </summary>
string ICustomTypeDescriptor.GetComponentName()
{
return null;
}
/// <summary>
/// Gets the Type Converter
/// </summary>
TypeConverter ICustomTypeDescriptor.GetConverter()
{
return null;
}
/// <summary>
/// Gets the Default Event
/// </summary>
/// <returns></returns>
EventDescriptor ICustomTypeDescriptor.GetDefaultEvent()
{
return null;
}
/// <summary>
/// Gets the Default Property
/// </summary>
PropertyDescriptor ICustomTypeDescriptor.GetDefaultProperty()
{
return null;
}
/// <summary>
/// Gets the Editor
/// </summary>
object ICustomTypeDescriptor.GetEditor(Type editorBaseType)
{
return null;
}
/// <summary>
/// Gets the Events
/// </summary>
EventDescriptorCollection ICustomTypeDescriptor.GetEvents(Attribute[] attributes)
{
return new EventDescriptorCollection(null);
}
/// <summary>
/// Gets the events
/// </summary>
EventDescriptorCollection ICustomTypeDescriptor.GetEvents()
{
return new EventDescriptorCollection(null);
}
/// <summary>
/// Gets the properties
/// </summary>
PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(Attribute[] attributes)
{
List<propertydescriptor> properties = new List<propertydescriptor>();
//Add property descriptors for each entry in the dictionary
foreach (string key in this.Keys)
{
properties.Add(new TestResultPropertyDescriptor(key));
}
//Get properties also belonging to this class also
PropertyDescriptorCollection pdc = TypeDescriptor.GetProperties(this.GetType(), attributes);
foreach (PropertyDescriptor oPropertyDescriptor in pdc)
{
properties.Add(oPropertyDescriptor);
}
return new PropertyDescriptorCollection(properties.ToArray());
}
/// <summary>
/// gets the Properties
/// </summary>
PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties()
{
return ((ICustomTypeDescriptor)this).GetProperties(null);
}
/// <summary>
/// Gets the property owner
/// </summary>
object ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor pd)
{
return this;
}
#endregion Methods
//---------------------------------------------------------------------------------------------------------------------------
}
Note: In the GetProperties method I Could Cache the PropertyDescriptors once read for performance but as I'm adding and removing columns at runtime I always want them rebuilt
You will also notice in the GetProperties method that the Property Descriptors added for the dictionary entries are of type TestResultPropertyDescriptor. This is a custom Property Descriptor class that manages how properties are set and retrieved. Take a look at the implementation below:
/// <summary>
/// Property Descriptor for Test Result Row Wrapper
/// </summary>
public class TestResultPropertyDescriptor : PropertyDescriptor
{
//- PROPERTIES --------------------------------------------------------------------------------------------------------------
#region Properties
/// <summary>
/// Component Type
/// </summary>
public override Type ComponentType
{
get { return typeof(Dictionary<string, TestResultValue>); }
}
/// <summary>
/// Gets whether its read only
/// </summary>
public override bool IsReadOnly
{
get { return false; }
}
/// <summary>
/// Gets the Property Type
/// </summary>
public override Type PropertyType
{
get { return typeof(string); }
}
#endregion Properties
//- CONSTRUCTOR -------------------------------------------------------------------------------------------------------------
#region Constructor
/// <summary>
/// Constructor
/// </summary>
public TestResultPropertyDescriptor(string key)
: base(key, null)
{
}
#endregion Constructor
//- METHODS -----------------------------------------------------------------------------------------------------------------
#region Methods
/// <summary>
/// Can Reset Value
/// </summary>
public override bool CanResetValue(object component)
{
return true;
}
/// <summary>
/// Gets the Value
/// </summary>
public override object GetValue(object component)
{
return ((Dictionary<string, TestResultValue>)component)[base.Name].Value;
}
/// <summary>
/// Resets the Value
/// </summary>
public override void ResetValue(object component)
{
((Dictionary<string, TestResultValue>)component)[base.Name].Value = string.Empty;
}
/// <summary>
/// Sets the value
/// </summary>
public override void SetValue(object component, object value)
{
((Dictionary<string, TestResultValue>)component)[base.Name].Value = value.ToString();
}
/// <summary>
/// Gets whether the value should be serialized
/// </summary>
public override bool ShouldSerializeValue(object component)
{
return false;
}
#endregion Methods
//---------------------------------------------------------------------------------------------------------------------------
}
The main properties to look at on this class are GetValue and SetValue. Here you can see the component being casted as a dictionary and the value of the key inside it being Set or retrieved. Its important that the dictionary in this class is the same type in the Row wrapper class otherwise the cast will fail. When the descriptor is created the key (property name) is passed in and is used to query the dictionary to get the correct value.
Taken from my blog at:
Prior to PHP 7, the session_start() function did not directly accept any configuration options. Now you can do it this way
<?php
// This sends a persistent cookie that lasts a day.
session_start([
'cookie_lifetime' => 86400,
]);
?>
Reference: https://php.net/manual/en/function.session-start.php#example-5976
Quick and dirty
use DB;
OR
\DB::table...
This error message can happen if you have duplicate entries/entities and run SaveChanges().
Try:
document.getElementById("foo").onclick = function (){alert('foo');};
clearfix
should contain the floating elements but in your html you have added clearfix
only after floating right that is your pull-right
so you should do like this:
<div class="clearfix">
<div id="sidebar">
<ul>
<li>A</li>
<li>A</li>
<li>C</li>
<li>D</li>
<li>E</li>
<li>F</li>
<li>...</li>
<li>Z</li>
</ul>
</div>
<div id="main">
<div>
<div class="pull-right">
<a>RIGHT</a>
</div>
</div>
<div>MOVED BELOW Z</div>
</div>
Happy to know you solved the problem by setting overflow properties. However this is also good idea to clear the float. Where you have floated your elements you could add overflow: hidden;
as you have done in your main.
HttpWebRequest myHttprequest = null;
HttpWebResponse myHttpresponse = null;
myHttpRequest = (HttpWebRequest)WebRequest.Create(URL);
myHttpRequest.Method = "POST";
myHttpRequest.ContentType = "application/x-www-form-urlencoded";
myHttpRequest.ContentLength = urinfo.Length;
StreamWriter writer = new StreamWriter(myHttprequest.GetRequestStream());
writer.Write(urinfo);
writer.Close();
myHttpresponse = (HttpWebResponse)myHttpRequest.GetResponse();
if (myHttpresponse.StatusCode == HttpStatusCode.OK)
{
//Perform necessary action based on response
}
myHttpresponse.Close();
git-bash
reports
fatal: Unable to create <Path to git repo>/.git/index.lock
: File exists.
Deleting index.lock
makes the error go away.
Here is the other solution to scale an imageView of UIButton.
button.imageView?.layer.transform = CATransform3DMakeScale(0.8, 0.8, 0.8)
This can be achieved with the onresize property of the GlobalEventHandlers interface in JavaScript, by assigning a function to the onresize property, like so:
window.onresize = functionRef;
The following code snippet demonstrates this, by console logging the innerWidth and innerHeight of the window whenever it's resized. (The resize event fires after the window has been resized)
function resize() {_x000D_
console.log("height: ", window.innerHeight, "px");_x000D_
console.log("width: ", window.innerWidth, "px");_x000D_
}_x000D_
_x000D_
window.onresize = resize;
_x000D_
<p>In order for this code snippet to work as intended, you will need to either shrink your browser window down to the size of this code snippet, or fullscreen this code snippet and resize from there.</p>
_x000D_
Your file will probably be cached - but it depends...
Different browsers have slightly different behaviors - most noticeably when dealing with ambiguous/limited caching headers emanating from the server. If you send a clear signal, the browsers obey, virtually all of the time.
The greatest variance by far, is in the default caching configuration of different web servers and application servers.
Some (e.g. Apache) are likely to serve known static file types with HTTP headers encouraging the browser to cache them, while other servers may send no-cache
commands with every response - regardless of filetype.
...
So, first off, read some of the excellent HTTP caching tutorials out there. HTTP Caching & Cache-Busting for Content Publishers was a real eye opener for me :-)
Next install and fiddle around with Firebug and the Live HTTP Headers add-on , to find out which headers your server is actually sending.
Then read your web server docs to find out how to tweak them to perfection (or talk your sysadmin into doing it for you).
...
As to what happens when the browser is restarted, it depends on the browser and the user configuration.
As a rule of thumb, expect the browser to be more likely to check in with the server after each restart, to see if anything has changed (see If-Last-Modified and If-None-Match).
If you configure your server correctly, it should be able to return a super-short 304 Not Modified (costing very little bandwidth) and after that the browser will use the cache as normal.
Firstly, you probably want to add a return false; to the bottom of your Submit() method in JavaScript (so it stops the submit, since you're handling it in AJAX).
You're connecting to the complete event, not the success event - there's a significant difference and that's why your debugging results aren't as expected. Also, I've never made the signature methods match yours, and I've always provided a contentType and dataType. For example:
$.ajax({
type: "POST",
url: "Default.aspx/OnSubmit",
data: dataValue,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
},
success: function (result) {
alert("We returned: " + result);
}
});
Note you can add the Microsoft.AspNetCore.WebUtilities
nuget package from Microsoft and then use this to append values to query string:
QueryHelpers.AddQueryString(longurl, "action", "login1")
QueryHelpers.AddQueryString(longurl, new Dictionary<string, string> { { "action", "login1" }, { "attempts", "11" } });
FYI: The other solutions will only log statements from the default database—usually postgres
—to log others; start with their solution; then:
ALTER DATABASE your_database_name
SET log_statement = 'all';
For me the problem was the port. I first incorrectly used port 465, which works for SSL
but not TLS
. So the key thing was changing the port to 587.
To configure your JRE in eclipse:
One very practical way to do this is to create a dummy start page for your tests that is simply a form with POST that has a single "start test" button and a bunch of <input type="hidden"
... elements with the appropriate post data.
For example you might create a SeleniumTestStart.html
page with these contents:
<body>
<form action="/index.php" method="post">
<input id="starttestbutton" type="submit" value="starttest"/>
<input type="hidden" name="stageid" value="stage-you-need-your-test-to-start-at"/>
</form>
</body>
In this example, index.php is where your normal web app is located.
The Selenium code at the start of your tests would then include:
open /SeleniumTestStart.html
clickAndWait starttestbutton
This is very similar to other mock and stub techniques used in automated testing. You are just mocking the entry point to the web app.
Obviously there are some limitations to this approach:
Please consider reading my article about the Qualities of an Ideal Test
it is not possible to import js file inside another js file
The way to use jquery inside js is
import the js in the html or whatever view page you are using inside which you are going to include the js file
view.html
<script src="<%=request.getContextPath()%>/js/jquery-1.11.3.js"></script>
<script src="<%=request.getContextPath()%>/js/default.js"></script>
default.js
$('document').ready(function() {
$('li#user').click(function() {
$(this).addClass('selectedEmp');
});
});
this will definitely work for you
If you don't have a file named Program.cs
, just add a new Class and name it Program.cs
.
Then paste this code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Sales {
static class Program {
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main() {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
If you want to avoid adding extra dependencies, I found node's process.argv
to be useful:
gulp.task('mytask', function() {
console.log(process.argv);
});
So the following:
gulp mytask --option 123
should display:
[ 'node', 'path/to/gulp.js', 'mytask', '--option', '123']
If you are sure that the desired parameter is in the right position, then the flags aren't needed.** Just use (in this case):
var option = process.argv[4]; //set to '123'
BUT: as the option may not be set, or may be in a different position, I feel that a better idea would be something like:
var option, i = process.argv.indexOf("--option");
if(i>-1) {
option = process.argv[i+1];
}
That way, you can handle variations in multiple options, like:
//task should still find 'option' variable in all cases
gulp mytask --newoption somestuff --option 123
gulp mytask --option 123 --newoption somestuff
gulp mytask --flag --option 123
** Edit: true for node scripts, but gulp interprets anything without a leading "--" as another task name. So using gulp mytask 123
will fail because gulp can't find a task called '123'.
Try LIKE
construction, e.g. (assuming StudentId
is of type Char
, VarChar
etc.)
select *
from Students
where StudentId like '%' || TEXT || '%' -- <- TEXT - text to contain
First of all, Thank you DTing for awesome answer. It's pretty much perfect.
For those who are suffering from not having GCC access in shared hosting, Go for ActivePython instead of normal python like Scott Stafford mentioned. Here are the commands for that.
wget http://downloads.activestate.com/ActivePython/releases/2.7.13.2713/ActivePython-2.7.13.2713-linux-x86_64-glibc-2.3.6-401785.tar.gz
tar -zxvf ActivePython-2.7.13.2713-linux-x86_64-glibc-2.3.6-401785.tar.gz
cd ActivePython-2.7.13.2713-linux-x86_64-glibc-2.3.6-401785
./install.sh
It will ask you path to python directory. Enter
../../.localpython
Just replace above as Step 1 in DTing's answer and go ahead with Step 2 after that. Please note that ActivePython package URL may change with new release. You can always get new URL from here : http://www.activestate.com/activepython/downloads
Based on URL you need to change the name of tar and cd command based on file received.
In XML Design
android:background="@drawable/imagename
android:src="@drawable/imagename"
Drawable Image via code
imageview.setImageResource(R.drawable.imagename);
Server image
## Dependency ##
implementation 'com.github.bumptech.glide:glide:4.7.1'
annotationProcessor 'com.github.bumptech.glide:compiler:4.7.1'
Glide.with(context).load(url) .placeholder(R.drawable.image)
.into(imageView);
## dependency ##
implementation 'com.squareup.picasso:picasso:2.71828'
Picasso.with(context).load(url) .placeholder(R.drawable.image)
.into(imageView);
While unzipping will reveal the resources, the AndroidManifest.xml
will be encoded. apktool
can – among lots of other things – also decode this file.
To decode the application App.apk
into the folder App
, run
apktool decode App.apk App
apktool
is not included in the official Android SDK, but available using most packet repositories.
Arbitrarily choosing to keep the minimum PIC_ID. Also, avoid using the implicit join syntax.
SELECT U.NAME, MIN(P.PIC_ID)
FROM USERS U
INNER JOIN POSTINGS P1
ON U.EMAIL_ID = P1.EMAIL_ID
INNER JOIN PICTURES P
ON P1.PIC_ID = P.PIC_ID
WHERE P.CAPTION LIKE '%car%'
GROUP BY U.NAME;
You can use the path
module to join the path of the directory in which helper1.js
lives to the relative path of foobar.json
. This will give you the absolute path to foobar.json
.
var fs = require('fs');
var path = require('path');
var jsonPath = path.join(__dirname, '..', 'config', 'dev', 'foobar.json');
var jsonString = fs.readFileSync(jsonPath, 'utf8');
This should work on Linux, OSX, and Windows assuming a UTF8 encoding.
There is a trick that always worked for me:
If you got and unexpected indent and you see that all the code is perfectly indented, try opening it with another editor and you will see what line of code is not indented.
It happened to me when used vim, gedit or editors like that.
Try to use only 1 editor for your code.
Since this topic is not close I'll post this answer, I hope this helps someone to understand why java does not allow multiple inheritance.
Consider the following class:
public class Abc{
public void doSomething(){
}
}
In this case the class Abc does not extends nothing right? Not so fast, this class implicit extends the class Object, base class that allow everything work in java. Everything is an object.
If you try to use the class above you'll see that your IDE allow you to use methods like: equals(Object o)
, toString()
, etc, but you didn't declare those methods, they came from the base class Object
You could try:
public class Abc extends String{
public void doSomething(){
}
}
This is fine, because your class will not implicit extends Object
but will extends String
because you said it. Consider the following change:
public class Abc{
public void doSomething(){
}
@Override
public String toString(){
return "hello";
}
}
Now your class will always return "hello" if you call toString().
Now imagine the following class:
public class Flyer{
public void makeFly(){
}
}
public class Bird extends Abc, Flyer{
public void doAnotherThing(){
}
}
Again class Flyer
implicit extends Object which has the method toString()
, any class will have this method since they all extends Object
indirectly, so, if you call toString()
from Bird
, which toString()
java would have to use? From Abc
or Flyer
? This will happen with any class that try to extends two or more classes, to avoid this kind of "method collision" they built the idea of interface, basically you could think them as an abstract class that does not extends Object indirectly. Since they are abstract they will have to be implemented by a class, which is an object (you cannot instanciate an interface alone, they must be implemented by a class), so everything will continue to work fine.
To differ classes from interfaces, the keyword implements was reserved just for interfaces.
You could implement any interface you like in the same class since they does not extends anything by default (but you could create a interface that extends another interface, but again, the "father" interface would not extends Object"), so an interface is just an interface and they will not suffer from "methods signature colissions", if they do the compiler will throw a warning to you and you will just have to change the method signature to fix it (signature = method name + params + return type).
public interface Flyer{
public void makeFly(); // <- method without implementation
}
public class Bird extends Abc implements Flyer{
public void doAnotherThing(){
}
@Override
public void makeFly(){ // <- implementation of Flyer interface
}
// Flyer does not have toString() method or any method from class Object,
// no method signature collision will happen here
}
Your question can be conveniently divided into several parts:
Does a VPN hide location? Yes, he is capable of this. This is not about GPS determining your location. If you try to change the region via VPN in an application that requires GPS access, nothing will work. However, sites define your region differently. They get an IP address and see what country or region it belongs to. If you can change your IP address, you can change your region. This is exactly what VPNs can do.
How to hide location on Android? There is nothing difficult in figuring out how to set up a VPN on Android, but a couple of nuances still need to be highlighted. Let's start with the fact that not all Android VPNs are created equal. For example, VeePN outperforms many other services in terms of efficiency in circumventing restrictions. It has 2500+ VPN servers and a powerful IP and DNS leak protection system.
You can easily change the location of your Android device by using a VPN. Follow these steps for any device model (Samsung, Sony, Huawei, etc.):
Download and install a trusted VPN.
Install the VPN on your Android device.
Open the application and connect to a server in a different country.
Your Android location will now be successfully changed!
Is it legal? Yes, changing your location on Android is legal. Likewise, you can change VPN settings in Microsoft Edge on your PC, and all this is within the law. VPN allows you to change your IP address, safeguarding your privacy and protecting your actual location from being exposed. However, VPN laws may vary from country to country. There are restrictions in some regions.
Brief summary: Yes, you can change your region on Android and a VPN is a necessary assistant for this. It's simple, safe and legal. Today, VPN is the best way to change the region and unblock sites with regional restrictions.
One option to try is to put the image in the drawable-nodpi
folder and set background of a layout to the drawable resource id.
This definitely works with scaling down, I haven't tested with scaling up though.
To be short, use:
write-output "your text" | out-file -append -encoding utf8 "filename"
Sometimes frameworks (like $resource/AngularJS) require an array as a query result, and you can't really have a response like {count:10,items:[...]}
in this case I store "count" in responseHeaders.
P. S. Actually you can do that with $resource/AngularJS, but it needs some tweaks.
If you're going to be doing this search frequently, consider changing the format of your object so dinner actually is a key. This is kind of like assigning a primary clustered key in a database table. So, for example:
Obj = { 'pizza' : { 'name' : 'bob' }, 'sushi' : { 'name' : 'john' } }
You can now easily access it like this: Object['sushi']['name']
Or if the object really is this simple (just 'name' in the object), you could just change it to:
Obj = { 'pizza' : 'bob', 'sushi' : 'john' }
And then access it like: Object['sushi']
.
It's obviously not always possible or to your advantage to restructure your data object like this, but the point is, sometimes the best answer is to consider whether your data object is structured the best way. Creating a key like this can be faster and create cleaner code.
setattr()
We use setattr to add an attribute to our class instance. We pass the class instance, the attribute name, and the value.
getattr()
With getattr we retrive these values
For example
Employee = type("Employee", (object,), dict())
employee = Employee()
# Set salary to 1000
setattr(employee,"salary", 1000 )
# Get the Salary
value = getattr(employee, "salary")
print(value)
this is what worked for me :
1 --> ng g module new-module
2 --> ng g c new-module/component-test --module=new-module/new-module.module.ts
If you want to generate a component without its directory use --flat
flag.
This worked good for me:
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {_x000D_
print("section: \(indexPath.section)")_x000D_
print("row: \(indexPath.row)")_x000D_
}
_x000D_
The output should be:
section: 0
row: 0
If it has to be really fast you can include a list of primes:
http://www.bigprimes.net/archive/prime/
If you just have to know if a certain number is a prime number, there are various prime tests listed on wikipedia. They are probably the fastest method to determine if large numbers are primes, especially because they can tell you if a number is not a prime.