I would recomend to use an external source for large color palettes.
http://tools.medialab.sciences-po.fr/iwanthue/
has a service to compose any size of palette according to various parameters and
discusses the generic problem from a graphics designers perspective and gives lots of examples of usable palettes.
To comprise a palette from RGB values you just have to copy the values in a vector as in e.g.:
colors37 = c("#466791","#60bf37","#953ada","#4fbe6c","#ce49d3","#a7b43d","#5a51dc","#d49f36","#552095","#507f2d","#db37aa","#84b67c","#a06fda","#df462a","#5b83db","#c76c2d","#4f49a3","#82702d","#dd6bbb","#334c22","#d83979","#55baad","#dc4555","#62aad3","#8c3025","#417d61","#862977","#bba672","#403367","#da8a6d","#a79cd4","#71482c","#c689d0","#6b2940","#d593a7","#895c8b","#bd5975")
This error, as correctly identified above, is due to the compiler not using c++11 or above standard. This answer is for Windows 10.
For c++11 and above standard support in codeblocks version 17:
Click settings in the toolbar.
A drop-down menu appears. Select compiler option.
Choose Global Compiler Settings.
In the toolbar in this new window in second section, choose compiler settings.
Then choose compiler flags option in below toolbar.
Unfold general tab. Check the C++ standard that you want your compiler to follow.
Click OK.
For those who are trying to get C++11 support in Sublime text.
Download mingw compiler version 7 or above. In versions below this, the default c++ standard used is c++98 whereas in versions higher than 7, the default standard used is c++11.
Copy the folder in main C drive. It should not be inside any other folder in C drive.
Rename the folder as MinGW. This name is case insensitive, so it should any variation of mingw and must not include any other characters in the name.
Then go to environment variables and edit the path variable. Add this "C:\mingw\bin" and click OK.
You can check the version of g++ in cmd by typing g++ -v
.
This should be sufficient to enable c++11 in sublime text.
If you want to take inputs and outputs as well from input files for competitive programming purposes, then follow this link.
What I did at the end was attach gdb to the process before it crashed, and then when it got the segfault I executed the generate-core-file
command. That forced generation of a core dump.
It is also possible to receive this error from a select component if the query fails in an unusual manner (eg: a sub-query returns multiple rows in an oracle oledb connection)
If you want to dynamically allocate arrays, you can use malloc
from stdlib.h
.
If you want to allocate an array of 100 elements using your words
struct, try the following:
words* array = (words*)malloc(sizeof(words) * 100);
The size of the memory that you want to allocate is passed into malloc
and then it will return a pointer of type void
(void*
). In most cases you'll probably want to cast it to the pointer type you desire, which in this case is words*
.
The sizeof
keyword is used here to find out the size of the words
struct, then that size is multiplied by the number of elements you want to allocate.
Once you are done, be sure to use free()
to free up the heap memory you used in order to prevent memory leaks:
free(array);
If you want to change the size of the allocated array, you can try to use realloc
as others have mentioned, but keep in mind that if you do many realloc
s you may end up fragmenting the memory. If you want to dynamically resize the array in order to keep a low memory footprint for your program, it may be better to not do too many realloc
s.
I just discovered this issue. I was able to get around it by using indirection. In each module define a function, lets call it indirect
:
function indirect(js) { return eval(js); }
With that function in each module, you can then execute any code in the context of it.
E.g. if you had this import in your module:
import { imported_fn } from "./import.js";
You could then get the results of calling imported_fn
from the console by doing this:
indirect("imported_fn()");
Using eval
was my first thought, but it doesn't work. My hypothesis is that calling eval
from the console remains in the context of console, and we need to execute in the context of the module.
The new recommended way to do this is to use the setNames
function. See
?setNames
. Since this creates a new copy of the data.frame
, be sure to assign the result to the original data.frame
, if that is your intention.
data_frame <- setNames(data_frame, c("premium","change","newprice"))
Newer versions of R will give you warning if you use colnames
in some of the ways suggested by earlier answers.
If this were a data.table
instead, you could use the data.table
function setnames
, which can modify specific column names or a single column name by reference:
setnames(data_table, "old-name", "new-name")
I think most of these solutions are far too complicated. I assume that in your test controller you have this
@Autowired
private ObjectMapper objectMapper;
If its a rest service
@Test
public void test() throws Exception {
mockMvc.perform(post("/person"))
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(new Person()))
...etc
}
For spring mvc using a posted form I came up with this solution. (Not really sure if its a good idea yet)
private MultiValueMap<String, String> toFormParams(Object o, Set<String> excludeFields) throws Exception {
ObjectReader reader = objectMapper.readerFor(Map.class);
Map<String, String> map = reader.readValue(objectMapper.writeValueAsString(o));
MultiValueMap<String, String> multiValueMap = new LinkedMultiValueMap<>();
map.entrySet().stream()
.filter(e -> !excludeFields.contains(e.getKey()))
.forEach(e -> multiValueMap.add(e.getKey(), (e.getValue() == null ? "" : e.getValue())));
return multiValueMap;
}
@Test
public void test() throws Exception {
MultiValueMap<String, String> formParams = toFormParams(new Phone(),
Set.of("id", "created"));
mockMvc.perform(post("/person"))
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.params(formParams))
...etc
}
The basic idea is to
- first convert object to json string to get all the field names easily
- convert this json string into a map and dump it into a MultiValueMap
that spring expects. Optionally filter out any fields you dont want to include (Or you could just annotate fields with @JsonIgnore
to avoid this extra step)
What you are looking for is disabled="true". Here is an example:
<textarea class="customPayload" disabled="true" *ngIf="!showSpinner"></textarea>
One thing to remember (or should I say recall) is that you cannot stack onload
s like you can with ready
. In other words, jQuery magic allows multiple ready
s on the same page, but you can't do that with onload
.
The last onload
will overrule any previous onload
s.
A nice way to deal with that is with a function apparently written by one Simon Willison and described in Using Multiple JavaScript Onload Functions.
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
}
else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}
// Example use:
addLoadEvent(nameOfSomeFunctionToRunOnPageLoad);
addLoadEvent(function() {
/* More code to run on page load */
});
You can use the 'netstat' command for this. There's a description of doing this sort of thing here.
Set the tagName as an explicit attribute:
for(var i=0,els=document.querySelectorAll('*'); i<els.length;
els[i].setAttribute('tagName',els[i++].tagName) );
I needed this myself, for an XML Document, with Nested Tags ending in _Sequence
. See JaredMcAteer answer for more details.
document.querySelectorAll('[tagName$="_Sequence"]')
I didn't say it would be pretty :)
PS: I would recommend to use tag_name
over tagName, so you do not run into interferences when reading 'computer generated', implicit DOM attributes.
You can import the whole module as follows:
import * as FriendCard from './../pages/FriendCard';
For more details please refer the modules section of Typescript official docs.
There are three "vanilla" ways to check this with or without jQuery.
First is to force boolean evaluation by coercion, then check if it's equal to the original value:
function isBoolean( n ) {
return !!n === n;
}
Doing a simple typeof
check:
function isBoolean( n ) {
return typeof n === 'boolean';
}
Doing a completely overkill and unnecessary instantiation of a class wrapper on a primative:
function isBoolean( n ) {
return n instanceof Boolean;
}
The third will only return true
if you create a new Boolean
class and pass that in.
To elaborate on primitives coercion (as shown in #1), all primitives types can be checked in this way:
Boolean
:
function isBoolean( n ) {
return !!n === n;
}
Number
:
function isNumber( n ) {
return +n === n;
}
String
:
function isString( n ) {
return ''+n === n;
}
Active Directory does not store the group membership on user objects. It only stores the Member list on the group. The tools show the group membership on user objects by doing queries for it.
How about:
(&(objectClass=group)(member=cn=my,ou=full,dc=domain))
(You forgot the (& ) bit in your example in the question as well).
// I used this code with the fpdf library.
// Este código lo usé con la libreria fpdf.
var datas = json1;
var xhr = new XMLHttpRequest();
xhr.open("POST", "carpeta/archivo.php");
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.responseType = "blob";
xhr.onload = function () {
if (this.status === 200) {
var blob = new Blob([xhr.response], {type: 'application/pdf'});
const url = window.URL.createObjectURL(blob);
window.open(url,"_blank");
setTimeout(function () {
// For Firefox it is necessary to delay revoking the ObjectURL
window.URL.revokeObjectURL(datas)
, 100
})
}
};
xhr.send("men="+datas);
I have an updated solution (late 2019) , to get 80% width of parent Responsively with Hooks it work's even if the device rotate.
You can use Dimensions.get('window').width
to get Device Width in this example you can see how you can do it Responsively
import React, { useEffect, useState } from 'react';
import { Dimensions , View , Text , StyleSheet } from 'react-native';
export default const AwesomeProject() => {
const [screenData, setScreenData] = useState(Dimensions.get('window').width);
useEffect(() => {
const onChange = () => {
setScreenData(Dimensions.get('window').width);
};
Dimensions.addEventListener('change', onChange);
return () => {Dimensions.removeEventListener('change', onChange);};
});
return (
<View style={[styles.container, { width: screenData * 0.8 }]}>
<Text> I'mAwesome </Text>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: '#eee',
},
});
here the link to webreports version 12 https://www.nuget.org/packages/Microsoft.ReportViewer.WebForms.v12/12.0.0?_src=template
after the package installed
on your toolbox browse the dll reference it to bin then that's it run the visual studio
Given a command like attrib
:
require 'open3'
a="attrib"
Open3.popen3(a) do |stdin, stdout, stderr|
puts stdout.read
end
I've found that while this method isn't as memorable as
system("thecommand")
or
`thecommand`
in backticks, a good thing about this method compared to other methods is
backticks don't seem to let me puts
the command I run/store the command I want to run in a variable, and system("thecommand")
doesn't seem to let me get the output whereas this method lets me do both of those things, and it lets me access stdin, stdout and stderr independently.
See "Executing commands in ruby" and Ruby's Open3 documentation.
See also How to prevent google chrome from caching my inputs, esp hidden ones when user click back? without which Chrome might reload but preserve the previous content of <input>
elements -- in other words, use autocomplete="off"
.
Here is an example that's working for me with MVC and Javascript in the Razor. The first function calls an action via ajax on my controller and passes two parameters.
function redirectToAction(var1, var2)
{
try{
var url = '../actionnameinsamecontroller/' + routeId;
$.ajax({
type: "GET",
url: url,
data: { param1: var1, param2: var2 },
dataType: 'html',
success: function(){
},
error: function(xhr, ajaxOptions, thrownError){
alert(error);
}
});
}
catch(err)
{
alert(err.message);
}
}
Use the ajaxStart to start your progress bar code.
$(document).ajaxStart(function(){
try
{
// showing a modal
$("#progressDialog").modal();
var i = 0;
var timeout = 750;
(function progressbar()
{
i++;
if(i < 1000)
{
// some code to make the progress bar move in a loop with a timeout to
// control the speed of the bar
iterateProgressBar();
setTimeout(progressbar, timeout);
}
}
)();
}
catch(err)
{
alert(err.message);
}
});
When the process completes close the progress bar
$(document).ajaxStop(function(){
// hide the progress bar
$("#progressDialog").modal('hide');
});
I resolved that problem just moving my project from E: to C:. I think it happened becouse nodejs and npm was installed in my C: and the project was in my E:
if ($("element class or id name").css("property") == "value") {
your code....
}
I would suggest making the div
s a little smaller and adding a margin of a percentage.
<div style="width:100%; height: 200px; background-color: grey;">_x000D_
<div style="width: 23%; float:left; margin: 1%; background-color: red;">A</div>_x000D_
<div style="width: 23%; float:left; margin: 1%; background-color: orange;">B</div>_x000D_
<div style="width: 23%; float:left; margin: 1%; background-color: green;">C</div>_x000D_
<div style="width: 23%; float:left; margin: 1%; background-color: blue;">D</div>_x000D_
</div>
_x000D_
0xe0434352 is the SEH code for a CLR exception. If you don't understand what that means, stop and read A Crash Course on the Depths of Win32™ Structured Exception Handling. So your process is not handling a CLR exception. Don't shoot the messenger, KERNELBASE.DLL is just the unfortunate victim. The perpetrator is MyApp.exe.
There should be a minidump of the crash in DrWatson folders with a full stack, it will contain everything you need to root cause the issue.
I suggest you wire up, in your myapp.exe code, AppDomain.UnhandledException
and Application.ThreadException
, as appropriate.
If you are looking for a custom code instead of plugin, then this might help you. Facebook graph has under gone some changes since it has evolved. These steps are for the latest Graph API which I tried recently and worked well.
There are two main steps involved - 1. Getting Facebook Access Token, 2. Calling the Graph API passing the access token.
1. Getting the access token - Here is the step by step process to get the access token for your Facebook page. - Embed Facebook page feed on my website. As per this you need to create an app in Facebook developers page which would give you an App Id and an App Secret. Use these two and get the Access Token.
2. Calling the Graph API - This would be pretty simple once you get the access token. You just need to form a URL to Graph API with all the fields/properties you want to retrieve and make a GET request to this URL. Here is one example on how to do it in asp.net MVC. Embedding facebook feeds using asp.net mvc. This should be pretty similar in any other technology as it would be just a HTTP GET request.
Sample FQL Query: https://graph.facebook.com/FBPageName/posts?fields=full_picture,picture,link,message,created_time&limit=5&access_token=YOUR_ACCESS_TOKEN_HERE
I would create a comparator for the person class that can be parametrized with a certain sorting behaviour. Here I can set the sorting order but it can be modified to allow sorting for other person attributes as well.
public class PersonComparator implements Comparator<Person> {
public enum SortOrder {ASCENDING, DESCENDING}
private SortOrder sortOrder;
public PersonComparator(SortOrder sortOrder) {
this.sortOrder = sortOrder;
}
@Override
public int compare(Person person1, Person person2) {
Integer age1 = person1.getAge();
Integer age2 = person2.getAge();
int compare = Math.signum(age1.compareTo(age2));
if (sortOrder == ASCENDING) {
return compare;
} else {
return compare * (-1);
}
}
}
(hope it compiles now, I have no IDE or JDK at hand, coded 'blind')
Edit
Thanks to Thomas, edited the code. I wouldn't say that the usage of Math.signum is good, performant, effective, but I'd like to keep it as a reminder, that the compareTo method can return any integer and multiplying by (-1) will fail if the implementation returns Integer.MIN_INTEGER... And I removed the setter because it's cheap enough to construct a new PersonComparator just when it's needed.
But I keep the boxing because it shows that I rely on an existing Comparable implementation. Could have done something like Comparable<Integer> age1 = new Integer(person1.getAge());
but that looked too ugly. The idea was to show a pattern which could easily be adapted to other Person attributes, like name, birthday as Date and so on.
Check this link , and last comment , You have to use WebChromeClient
for your purpose.
.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.
The problem is that buttonClickedEvent
is a member function and you need a pointer to member in order to invoke it.
Try this:
void (MyClass::*func)(int);
func = &MyClass::buttonClickedEvent;
And then when you invoke it, you need an object of type MyClass
to do so, for example this
:
(this->*func)(<argument>);
http://www.codeguru.com/cpp/cpp/article.php/c17401/C-Tutorial-PointertoMember-Function.htm
You can specify any amount of URLs on the command line. They will be fetched in a sequential manner in the specified order.
The simplest way I use in Visual Studio Code (Ubuntu) is:
Select the text which you want to format with the mouse.
Right click and choose "Format selection".
The biggest problem with your code is that it's unreadable. Python code rule number one, if it's not readable, no one's gonna look at it for long enough to get any useful information out of it. Always use descriptive variable names. Almost didn't catch the bug in your code, let's see it again with good names, slow-motion replay style:
to_modify = [5,4,3,2,1,0]
indexes = [0,1,3,5]
replacements = [0,0,0,0]
for index in indexes:
to_modify[indexes[index]] = replacements[index]
# to_modify[indexes[index]]
# indexes[index]
# Yo dawg, I heard you liked indexes, so I put an index inside your indexes
# so you can go out of bounds while you go out of bounds.
As is obvious when you use descriptive variable names, you're indexing the list of indexes with values from itself, which doesn't make sense in this case.
Also when iterating through 2 lists in parallel I like to use the zip
function (or izip
if you're worried about memory consumption, but I'm not one of those iteration purists). So try this instead.
for (index, replacement) in zip(indexes, replacements):
to_modify[index] = replacement
If your problem is only working with lists of numbers then I'd say that @steabert has the answer you were looking for with that numpy stuff. However you can't use sequences or other variable-sized data types as elements of numpy arrays, so if your variable to_modify
has anything like that in it, you're probably best off doing it with a for loop.
Fixed it...
Get-ChildItem C:\Windows\ -recurse -include @("*.txt*","*.pdf") |
Where-Object {$_.CreationTime -gt "01/01/2013" -and $_.CreationTime -lt "12/02/2014"} |
Select-Object FullName, CreationTime, @{Name="Mbytes";Expression={$_.Length/1Kb}}, @{Name="Age";Expression={(((Get-Date) - $_.CreationTime).Days)}} |
Export-Csv C:\search_TXT-and-PDF_files_01012013-to-12022014_sort.txt
can also appear if:
struct foo { int x, int y, int z }foo;
foo.x=12
instead of
struct foo { int x; int y; int z; }foo;
foo.x=12
There is another way to archive it.
In the BaseController
class create a method that returns a Model class like for instance.
public MenuPageModel GetTopMenu() { var m = new MenuPageModel(); // populate your model here return m; }
Layout
page you can call that method GetTopMenu()
@using GJob.Controllers <header class="header-wrapper border-bottom border-secondary"> <div class="sticky-header" id="appTopMenu"> @{ var menuPageModel = ((BaseController)this.ViewContext.Controller).GetTopMenu(); } @Html.Partial("_TopMainMenu", menuPageModel) </div> </header>
Laravel 5.3 use pluck($value, $key )
$value is displayed in your drop list and $key is id
controller
$products = Product::pluck('name', 'id');
return view('main.index', compact('products'));
view
{{ Form::select('id', $products, null, ['class' => 'form-control']) }}
I was solving this algorithm and get stuck with the pairs part.
This explanation help me a lot https://betterexplained.com/articles/techniques-for-adding-the-numbers-1-to-100/
So to calculate the sum of series of numbers:
n(n+1)/2
But you need to calculate this
1 + 2 + ... + (n-1)
So in order to get this you can use
n(n+1)/2 - n
that is equal to
n(n-1)/2
IntelliJ IDEA detects errors and warnings in the current file on the fly (unless Power Save Mode is activated in the File
menu).
Errors in other files and in the project view will be shown after Build
| Make
and listed in the Messages tool window.
For Bazel users: Project errors will show on Bazel Problems tool window after running Compile Project
(Ctrl/Cmd+F9)
To navigate between errors use Navigate
| Next Highlighted Error
(F2) / Previous Highlighted Error
(Shift+F2).
Error Stripe Mark color can be changed here:
You're looking for the zip builtin function. From the docs:
>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> zipped = zip(x, y)
>>> zipped
[(1, 4), (2, 5), (3, 6)]
This is pretty simple with numpy
, just subtract the arrays:
diffs = array1 - array2
I get:
diffs == array([ 0.1, 0.2, 0.3])
I encountered this issue when trying to debug with VSCode, so just wanted to add this is how you can add the argument to your debug setup.
You can add it to the runtimeArgs
property of your config in launch.json
.
See example below.
{
"version": "0.2.0",
"configurations": [{
"type": "node",
"request": "launch",
"name": "Launch Program",
"program": "${workspaceRoot}\\server.js"
},
{
"type": "node",
"request": "launch",
"name": "Launch Training Script",
"program": "${workspaceRoot}\\training-script.js",
"runtimeArgs": [
"--max-old-space-size=4096"
]
}
]}
INSERT INTO wp_bp_activity
(
user_id,
component,
`type`,
`action`,
content,
primary_link,
item_id,
secondary_item_id,
date_recorded,
hide_sitewide,
mptt_left,
mptt_right
)
VALUES(
1,'activity','activity_update','<a title="admin" href="http://brandnewmusicreleases.com/social-network/members/admin/">admin</a> posted an update','<a title="242925_1" href="http://brandnewmusicreleases.com/social-network/wp-content/uploads/242925_1.jpg" class="buddyboss-pics-picture-link">242925_1</a>','http://brandnewmusicreleases.com/social-network/members/admin/',' ',' ','2012-06-22 12:39:07',0,0,0
)
An example with VBScript (.vbs)
Sub sety(wsh, action, typey, vary, value)
Dim wu
Set wu = wsh.Environment(typey)
wui = wu.Item(vary)
Select Case action
Case "ls"
WScript.Echo wui
Case "del"
On Error Resume Next
wu.remove(vary)
On Error Goto 0
Case "set"
wu.Item(vary) = value
Case "add"
If wui = "" Then
wu.Item(vary) = value
ElseIf InStr(UCase(";" & wui & ";"), UCase(";" & value & ";")) = 0 Then
wu.Item(vary) = value & ";" & wui
End If
Case Else
WScript.Echo "Bad action"
End Select
End Sub
Dim wsh, args
Set wsh = WScript.CreateObject("WScript.Shell")
Set args = WScript.Arguments
Select Case WScript.Arguments.Length
Case 3
value = ""
Case 4
value = args(3)
Case Else
WScript.Echo "Arguments - 0: ls,del,set,add; 1: user,system, 2: variable; 3: value"
value = "```"
End Select
If Not value = "```" Then
' 0: ls,del,set,add; 1: user,system, 2: variable; 3: value
sety wsh, args(0), args(1), UCase(args(2)), value
End If
The relative reference would be
<img src="../images/logo.png">
If you know the location relative to the root of the server, that may be simplest approach for an app with a complex nested directory hierarchy - it would be the same from all folders.
For example, if your directory tree depicted in your question is relative to the root of the server, then index.html and sub_folder/sub.html would both use:
<img src="/images/logo.png">
If the images folder is instead in the root of an application like foo
below the server root (e.g. http://www.example.com/foo
), then index.html (http://www.example.com/foo/index.html
) e.g and sub_folder/sub.html (http://www.example.com/foo/sub_folder/sub.html
) both use:
<img src="/foo/images/logo.png">
You can filter using index
of array.
var months = ['Jan', 'March', 'April', 'June'];_x000D_
months = months.filter((month,idx) => idx < 2)_x000D_
console.log(months);
_x000D_
I would suggest to read up a bit on the syntax. See here.
if (dsnt<0.05) {
wilcox.test(distance[result=='nt'],distance[result=='t'],alternative=c("two.sided"),paired=TRUE)
} else if (dst<0.05) {
wilcox.test(distance[result=='nt'],distance[result=='t'],alternative=c("two.sided"),paired=TRUE)
} else
t.test(distance[result=='nt'],distance[result=='t'],alternative=c("two.sided"),paired=TRUE)
You can make the distinction explicit by adding another dimension to the array.
>>> a = np.array([1, 2, 3])
>>> a
array([1, 2, 3])
>>> a.transpose()
array([1, 2, 3])
>>> a.dot(a.transpose())
14
Now force it to be a column vector:
>>> a.shape = (3,1)
>>> a
array([[1],
[2],
[3]])
>>> a.transpose()
array([[1, 2, 3]])
>>> a.dot(a.transpose())
array([[1, 2, 3],
[2, 4, 6],
[3, 6, 9]])
Another option is to use np.newaxis when you want to make the distinction:
>>> a = np.array([1, 2, 3])
>>> a
array([1, 2, 3])
>>> a[:, np.newaxis]
array([[1],
[2],
[3]])
>>> a[np.newaxis, :]
array([[1, 2, 3]])
I know this is an old post, but the suggested answers didn't work on my end. I want to leave this here just in case someone will find it useful.
What i did is:
@Override
public void onResume() {
super.onResume();
// add all fragments
FragmentTransaction fragmentTransaction = getChildFragmentManager().beginTransaction();
for(Fragment fragment : fragmentPages){
String tag = fragment.getClass().getSimpleName();
fragmentTransaction.add(R.id.contentPanel, fragment, tag);
if(fragmentPages.indexOf(fragment) != currentPosition){
fragmentTransaction.hide(fragment);
} else {
lastTag = tag;
}
}
fragmentTransaction.commit();
}
Then in:
@Override
public void onPause() {
super.onPause();
// remove all attached fragments
for(Fragment fragment: fragmentPages){
getChildFragmentManager().beginTransaction().remove(fragment).commit();
}
}
there is a simple way for delete and put request, you can simply do it by adding a "_method
" parameter to your post request and write "PUT
" or "DELETE
" for its value!
Please run below script in your terminal
curl -X POST \
-H "Authorization: key= write here api_key" \
-H "Content-Type: application/json" \
-d '{
"registration_ids": [
"write here reg_id generated by gcm"
],
"data": {
"message": "Manual push notification from Rajkumar"
},
"priority": "high"
}' \
https://android.googleapis.com/gcm/send
it will give the message if it is succeeded or failed
I am working on an application in which we track live route. Passenger wants to show current position of driver and the expected arrival time to reach at his/her location. So I need to add some duration into current time.
So I found the below mentioned way to do the same. We can add any duration(hour,minutes and seconds) in our current time by moment:
var travelTime = moment().add(642, 'seconds').format('hh:mm A');// it will add 642 seconds in the current time and will give time in 03:35 PM format
var travelTime = moment().add(11, 'minutes').format('hh:mm A');// it will add 11 mins in the current time and will give time in 03:35 PM format; can use m or minutes
var travelTime = moment().add(2, 'hours').format('hh:mm A');// it will add 2 hours in the current time and will give time in 03:35 PM format
It fulfills my requirement. May be it can help you.
Quick answer
On src, you can always specify files to ignore using "!".
Example (you want to exclude all *.min.js files on your js folder and subfolder:
gulp.src(['js/**/*.js', '!js/**/*.min.js'])
You can do it as well for individual files.
Expanded answer:
Extracted from gulp documentation:
gulp.src(globs[, options])
Emits files matching provided glob or an array of globs. Returns a stream of Vinyl files that can be piped to plugins.
glob refers to node-glob syntax or it can be a direct file path.
So, looking to node-glob documentation we can see that it uses the minimatch library to do its matching.
On minimatch documentation, they point out the following:
if the pattern starts with a ! character, then it is negated.
And that is why using ! symbol will exclude files / directories from a gulp task
Here is a sample to find if there are match elements in another list
List<int> nums1 = new List<int> { 2, 4, 6, 8, 10 };
List<int> nums2 = new List<int> { 1, 3, 6, 9, 12};
if (nums1.Any(x => nums2.Any(y => y == x)))
{
Console.WriteLine("There are equal elements");
}
else
{
Console.WriteLine("No Match Found!");
}
I threw CMS's excellent answer into a quick jQuery extension:
(function($, window) {
$.fn.replaceOptions = function(options) {
var self, $option;
this.empty();
self = this;
$.each(options, function(index, option) {
$option = $("<option></option>")
.attr("value", option.value)
.text(option.text);
self.append($option);
});
};
})(jQuery, window);
It expects an array of objects which contain "text" and "value" keys. So usage is as follows:
var options = [
{text: "one", value: 1},
{text: "two", value: 2}
];
$("#foo").replaceOptions(options);
If you have seaborn
installed, an easier method that does not require you to perform pivot
:
import seaborn as sns
sns.lineplot(data=df, x='x', y='y', hue='color')
There are two parts to the model, the model definition, saved by Supervisor
as graph.pbtxt
in the model directory and the numerical values of tensors, saved into checkpoint files like model.ckpt-1003418
.
The model definition can be restored using tf.import_graph_def
, and the weights are restored using Saver
.
However, Saver
uses special collection holding list of variables that's attached to the model Graph, and this collection is not initialized using import_graph_def, so you can't use the two together at the moment (it's on our roadmap to fix). For now, you have to use approach of Ryan Sepassi -- manually construct a graph with identical node names, and use Saver
to load the weights into it.
(Alternatively you could hack it by using by using import_graph_def
, creating variables manually, and using tf.add_to_collection(tf.GraphKeys.VARIABLES, variable)
for each variable, then using Saver
)
@Keith -
In your comparison between IEnumerable<int> and IEnumerable<double> you don't need to worry - if you pass the wrong type your code won't compile anyway.
That isn't quite true - if a method is overloaded to both IEnumerable<int> and IEnumerable<double> then it may silently pass the unexpected inferred type (due to some other change in the program) to the wrong overload hence causing incorrect behaviour.
I suppose the question is how likely it is that this sort of situation will come up!
I guess part of the problem is how much confusion var adds to a given declaration - if it's not clear what type something is (despite being strongly typed and the compiler understanding entirely what type it is) someone might gloss over a type safety error, or at least take longer to understand a piece of code.
In Oracle 12c and above, we have two types of databases:
If you want to create an user, you have two possibilities:
You can create a "container user" aka "common user".
Common users belong to CBDs as well as to current and future PDBs. It means they can perform operations in Container DBs or Pluggable DBs according to assigned privileges.
create user c##username identified by password;
You can create a "pluggable user" aka "local user".
Local users belong only to a single PDB. These users may be given administrative privileges, but only for that PDB inside which they exist. For that, you should connect to pluggable datable like that:
alter session set container = nameofyourpluggabledatabase;
and there, you can create user like usually:
create user username identified by password;
Don't forget to specify the tablespace(s) to use, it can be useful during import/export of your DBs. See this for more information about it https://docs.oracle.com/database/121/SQLRF/statements_8003.htm#SQLRF01503
i was doing this way its working
keytool.exe -list -v -alias ALIAS_NAME -keystore "E:\MID_PATH\trackMeeKeyStore.jks" -storepass PASS -keypass PASS
A slight modification beyond @udondan's answer. I like to reuse the registered variable names with the set_fact
to help keep the clutter to a minimum.
So if I were to register using the variable, psk
, I'd use that same variable name with creating the set_fact
.
- name: generate PSK
shell: openssl rand -base64 48
register: psk
delegate_to: 127.0.0.1
run_once: true
- set_fact:
psk={{ psk.stdout }}
- debug: var=psk
run_once: true
Then when I run it:
$ ansible-playbook -i inventory setup_ipsec.yml
PLAY [all] *************************************************************************************************************************************************************************
TASK [Gathering Facts] *************************************************************************************************************************************************************
ok: [hostc.mydom.com]
ok: [hostb.mydom.com]
ok: [hosta.mydom.com]
TASK [libreswan : generate PSK] ****************************************************************************************************************************************************
changed: [hosta.mydom.com -> 127.0.0.1]
TASK [libreswan : set_fact] ********************************************************************************************************************************************************
ok: [hosta.mydom.com]
ok: [hostb.mydom.com]
ok: [hostc.mydom.com]
TASK [libreswan : debug] ***********************************************************************************************************************************************************
ok: [hosta.mydom.com] => {
"psk": "6Tx/4CPBa1xmQ9A6yKi7ifONgoYAXfbo50WXPc1kGcird7u/pVso/vQtz+WdBIvo"
}
PLAY RECAP *************************************************************************************************************************************************************************
hosta.mydom.com : ok=4 changed=1 unreachable=0 failed=0
hostb.mydom.com : ok=2 changed=0 unreachable=0 failed=0
hostc.mydom.com : ok=2 changed=0 unreachable=0 failed=0
I won't address the READ UNCOMMITTED
argument, just your original question.
Yes, you need WITH(NOLOCK)
on each table of the join. No, your queries are not the same.
Try this exercise. Begin a transaction and insert a row into table1 and table2. Don't commit or rollback the transaction yet. At this point your first query will return successfully and include the uncommitted rows; your second query won't return because table2 doesn't have the WITH(NOLOCK)
hint on it.
High-Level Design (HLD) involves decomposing a system into modules, and representing the interfaces & invocation relationships among modules. An HLD is referred to as software architecture.
LLD, also known as a detailed design, is used to design internals of the individual modules identified during HLD i.e. data structures and algorithms of the modules are designed and documented.
Now, HLD and LLD are actually used in traditional Approach (Function-Oriented Software Design) whereas, in OOAD, the system is seen as a set of objects interacting with each other.
As per the above definitions, a high-level design document will usually include a high-level architecture diagram depicting the components, interfaces, and networks that need to be further specified or developed. The document may also depict or otherwise refer to work flows and/or data flows between component systems.
Class diagrams with all the methods and relations between classes come under LLD. Program specs are covered under LLD. LLD describes each and every module in an elaborate manner so that the programmer can directly code the program based on it. There will be at least 1 document for each module. The LLD will contain - a detailed functional logic of the module in pseudo code - database tables with all elements including their type and size - all interface details with complete API references(both requests and responses) - all dependency issues - error message listings - complete inputs and outputs for a module.
I add this answer because I think it could be useful to anybody.
I step into the problem of setting RGBA colors (that is, RGB color with an Alpha value for transparency) for color display labels in my painting application.
As I came across the first answer, I was unable to set an RGBA color. I have also tried things like:
myLabel.setStyleSheet("QLabel { background-color : %s"%color.name())
where color
is an RGBA color.
So, my dirty solution was to extend QLabel
and override paintEvent()
method filling its bounding rect.
Today, I've open up the qt-assistant
and read the style reference properties list. Affortunately, it has an example that states the following:
QLineEdit { background-color: rgb(255, 0, 0) }
Thats open up my mind in doing something like the code below, as an example:
myLabel= QLabel()
myLabel.setAutoFillBackground(True) # This is important!!
color = QtGui.QColor(233, 10, 150)
alpha = 140
values = "{r}, {g}, {b}, {a}".format(r = color.red(),
g = color.green(),
b = color.blue(),
a = alpha
)
myLabel.setStyleSheet("QLabel { background-color: rgba("+values+"); }")
Note that setAutoFillBackground()
set in False
will not make it work.
Regards,
If you are using C++, try to use new/delete instead of malloc/calloc as they are operators. For malloc/calloc, you need to include another header. Don't mix two different languages in the same code. Their work is similar in every manner, both allocates memory dynamically from heap segment in hash table.
According to this link, it solved by entering this command:
export LC_ALL=C
Abstract: Steps of How to resolve "Serial port 'COM1' not found" in fedora 17.
Today install the packages for Arduino in Fedora 17. (yum install arduino) and I have the same problem: I decided to upload an example to the chip. and got the same error "Serial port 'COM1' not found".
In this case when I run Arduino program, some banner appears which warns me that my user is not in 'dialout' and 'lock' group. Do you want add your user in this groups? I click in add button, but for some reason the program fail and not say nothing.
Step1: recognize the Arduino device unplug your Arduino and list /dev files:
#ls -l /dev
plug your Arduino and go and list /dev files
#ls -l /dev
Find the new file (device) that was not before plugging, for example:
ttyACM0 or ttyUSB1
Read this properties:
ls -l /dev/ttyACM0
crw-rw---- 1 root dialout 166, 0 Dec 24 19:25 /dev/ttyACM0
the first c mean that Arduino is a character device.
user owner: root
group owner: dialout
mayor number: 166
minor number: 0
Step2: set your user as group owner.
If you do:
groups <yourUser>
And you are not in 'dialout' and/or 'lock' group. Add yourself in this groups run as root:
usermod -aG lock <yourUser>
usermod -aG dialout <yourUser>
restart the pc, and set /dev/<yourDeviceFile>
as your serial port before upload.
Assuming Python 3 (in Python 2, this difference is a little less well-defined) - a string is a sequence of characters, ie unicode codepoints; these are an abstract concept, and can't be directly stored on disk. A byte string is a sequence of, unsurprisingly, bytes - things that can be stored on disk. The mapping between them is an encoding - there are quite a lot of these (and infinitely many are possible) - and you need to know which applies in the particular case in order to do the conversion, since a different encoding may map the same bytes to a different string:
>>> b'\xcf\x84o\xcf\x81\xce\xbdo\xcf\x82'.decode('utf-16')
'?????'
>>> b'\xcf\x84o\xcf\x81\xce\xbdo\xcf\x82'.decode('utf-8')
'to??o?'
Once you know which one to use, you can use the .decode()
method of the byte string to get the right character string from it as above. For completeness, the .encode()
method of a character string goes the opposite way:
>>> 'to??o?'.encode('utf-8')
b'\xcf\x84o\xcf\x81\xce\xbdo\xcf\x82'
In some cases, there is no difference in file versions, but only in indentation, spacing, line ending or line numbers.
To patch despite those differences, it's possible to use the following two arguments :
--ignore-whitespace : It ignores whitespace differences (indentation, etc).
--fuzz 3 : the "--fuzz X" option sets the maximum fuzz factor to lines. This option only applies to context and unified diffs; it ignores up to X lines while looking for the place to install a hunk. Note that a larger fuzz factor increases the odds of making a faulty patch. The default fuzz factor is 2; there is no point to setting it to more than the number of lines of context in the diff, ordinarily 3.
Don't forget to user "--dry-run" : It'll try the patch without applying it.
Example :
patch --verbose --dry-run --ignore-whitespace --fuzz 3 < /path/to/patch.patch
More informations about Fuzz :
https://www.gnu.org/software/diffutils/manual/html_node/Inexact.html
Add to your settings.py
:
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'file': {
'level': 'DEBUG',
'class': 'logging.FileHandler',
'filename': 'debug.log',
},
},
'loggers': {
'django': {
'handlers': ['file'],
'level': 'DEBUG',
'propagate': True,
},
},
}
And it will create a file called debug.log
in the root of your.
https://docs.djangoproject.com/en/1.10/topics/logging/
Solution native Javascript :
document.getElementById("theSelectId").insertBefore(new Option('', ''), document.getElementById("theSelectId").firstChild);
example : http://codepen.io/anon/pen/GprybL
No real need for the JSON.NET package. You could use JavaScriptSerializer
. The Serialize
method will turn a managed type instance into a JSON string.
var serializer = new JavaScriptSerializer();
var json = serializer.Serialize(instanceOfThing);
There are two ways of storing a color with alpha. The first is exactly as you see it, with each component as-is. The second is to use pre-multiplied alpha, where the color values are multiplied by the alpha after converting it to the range 0.0-1.0; this is done to make compositing easier. Ordinarily you shouldn't notice or care which way is implemented by any particular engine, but there are corner cases where you might, for example if you tried to increase the opacity of the color. If you use rgba(0, 0, 0, 0)
you are less likely to to see a difference between the two approaches.
This is another method . Passing array as a pointer to the function
void generateArray(int *array, int size) {
srand(time(0));
for (int j=0;j<size;j++)
array[j]=(0+rand()%9);
}
int main(){
const int size=5;
int a[size];
generateArray(a, size);
return 0;
}
1.add a Data Conversion tool from toolbox
2.Open it,It shows all coloumns from excel ,convert it to desire output. take note of the Output Alias of
each applicable column (they are named Copy Of [original column name] by default)
3.now, in the Destination step, click on Mappings
To get a count of the number of unique combinations of id
, name
and address
:
SELECT Count(*)
FROM (
SELECT DISTINCT
id
, name
, address
FROM your_table
) As distinctified
After several tries, I got it! I'm setting the keyboard values programmatically like this:
myEditText.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_PASSWORD);
Or if you want you can edit the XML like so:
android: inputType = "numberPassword"
Both configs will display password bullets, so we need to create a custom ClickableSpan
class:
private class NumericKeyBoardTransformationMethod extends PasswordTransformationMethod {
@Override
public CharSequence getTransformation(CharSequence source, View view) {
return source;
}
}
Finally we need to implement it on the EditText
in order to display the characters typed.
myEditText.setTransformationMethod(new NumericKeyBoardTransformationMethod());
This is how my keyboard looks like now:
An orthodox way to achieve it, is by defining a new function:
public static String join(String joinStr, String... strings) {
if (strings == null || strings.length == 0) {
return "";
} else if (strings.length == 1) {
return strings[0];
} else {
StringBuilder sb = new StringBuilder(strings.length * 1 + strings[0].length());
sb.append(strings[0]);
for (int i = 1; i < strings.length; i++) {
sb.append(joinStr).append(strings[i]);
}
return sb.toString();
}
}
Sample:
String[] array = new String[] { "7, 7, 7", "Bill", "Bob", "Steve",
"[Bill]", "1,2,3", "Apple ][","~,~" };
String joined;
joined = join(" and ","7, 7, 7", "Bill", "Bob", "Steve", "[Bill]", "1,2,3", "Apple ][","~,~");
joined = join(" and ", array); // same result
System.out.println(joined);
Output:
7, 7, 7 and Bill and Bob and Steve and [Bill] and 1,2,3 and Apple ][ and ~,~
You can parse the list as a string and use of the eval
builtin function to read it as a list. In this case, you will have to put single quotes into double quote (or the way around) in order to ensure successful string parse.
# declare the list arg as a string
parser.add_argument('-l', '--list', type=str)
# parse
args = parser.parse()
# turn the 'list' string argument into a list object
args.list = eval(args.list)
print(list)
print(type(list))
Testing:
python list_arg.py --list "[1, 2, 3]"
[1, 2, 3]
<class 'list'>
Since Mockito 2.0 there's also possibility to use static method Matchers.argThat(ArgumentMatcher). With the help of Java 8 it is now much cleaner and more readable to write:
verify(mockBar).doSth(argThat((arg) -> arg.getSurname().equals("OneSurname")));
verify(mockBar).doSth(argThat((arg) -> arg.getSurname().equals("AnotherSurname")));
If you're tied to lower Java version there's also not-that-bad:
verify(mockBar).doSth(argThat(new ArgumentMatcher<Employee>() {
@Override
public boolean matches(Object emp) {
return ((Employee) emp).getSurname().equals("SomeSurname");
}
}));
Of course none of those can verify order of calls - for which you should use InOrder :
InOrder inOrder = inOrder(mockBar);
inOrder.verify(mockBar).doSth(argThat((arg) -> arg.getSurname().equals("FirstSurname")));
inOrder.verify(mockBar).doSth(argThat((arg) -> arg.getSurname().equals("SecondSurname")));
Please take a look at mockito-java8 project which makes possible to make calls such as:
verify(mockBar).doSth(assertArg(arg -> assertThat(arg.getSurname()).isEqualTo("Surname")));
You must specify your file in the copy:
xcopy C:\source\myfile.txt C:\target
Or if you want to copy all txt files for example
xcopy C:\source\*.txt C:\target
Improving Suman.hassan95's answer by adding a link to subcategory as well. Replace the following code:
$sub_cats = get_categories( $args2 );
if($sub_cats) {
foreach($sub_cats as $sub_category) {
echo $sub_category->name ;
}
}
with:
$sub_cats = get_categories( $args2 );
if($sub_cats) {
foreach($sub_cats as $sub_category) {
echo '<br/><a href="'. get_term_link($sub_category->slug, 'product_cat') .'">'. $sub_category->name .'</a>';
}
}
or if you also wish a counter for each subcategory, replace with this:
$sub_cats = get_categories( $args2 );
if($sub_cats) {
foreach($sub_cats as $sub_category) {
echo '<br/><a href="'. get_term_link($sub_category->slug, 'product_cat') .'">'. $sub_category->name .'</a>';
echo apply_filters( 'woocommerce_subcategory_count_html', ' <span class="cat-count">' . $sub_category->count . '</span>', $category );
}
}
Thanks to Mike's comment, I've re-read the doc and I've realised that my current user (i.e. userA that already has the create privilege) wasn't a direct/indirect member of the new owning role...
So the solution was quite simple - I've just done this grant:
grant userB to userA;
That's all folks ;-)
Another requirement is that the object has to be owned by user userA before altering it...
DECLARE
v_max NUMBER;
BEGIN
SELECT (NVL (MAX (<COLUMN_NAME>), 0) + 1) INTO v_max FROM <TABLE_NAME>;
EXECUTE IMMEDIATE 'CREATE SEQUENCE <SEQUENCE_NAME> INCREMENT BY 1 START WITH ' || v_max || ' NOCYCLE CACHE 20 NOORDER';
END;
I could do it like this
You are missing spring-security-web-3.1.X.RELEASE.jar
from your classpath
This is not an answer to your original question: "Appending output of a Batch file To log file?"
For reference, it's an answer to your followup question: "What lines should i add to my batch file which will make it execute after every 30mins?"
(But I would take Jon Skeet's advice: "You probably shouldn't do that in your batch file - instead, use Task Scheduler.")
Timeout:
Example (1 second):
TIMEOUT /T 1000 /NOBREAK
Sleep:
Example (1 second):
sleep -m 1000
Alternative methods:
Here's an answer to your 2nd followup question: "Along with the Timestamp?"
Create a date and time stamp in your batch files
Example:
echo *** Date: %DATE:/=-% and Time:%TIME::=-% *** >> output.log
To quickly fetch the causing exception without the need to re-code or rebuild, set a breakpoint on
org.hibernate.ejb.TransactionImpl.setRollbackOnly() // Hibernate < 4.3, or
org.hibernate.jpa.internal.TransactionImpl() // as of Hibernate 4.3
and go up in the stack, usually to some Interceptor. There you can read the causing exception from some catch block.
This is easily the simplest solution. For those who don't know how to do this:
Install the C++ compiler https://visualstudio.microsoft.com/downloads/#build-tools-for-visual-studio-2019
Go to the installation folder (In my case it is): C:\Program Files (x86)\Microsoft Visual C++ Build Tools
Open Visual C++ 2015 x86 x64 Cross Build Tools Command Prompt
Type: pip install package_name
In my case the error appeared when I added the com.nimbusds
library in my application deployed on Websphere 8.5
.
The below exception occurred:
Caused by: java.lang.IncompatibleClassChangeError: org.objectweb.asm.AnnotationVisitor
The solution was to exclude the asm jar from the library:
<dependency>
<groupId>com.nimbusds</groupId>
<artifactId>nimbus-jose-jwt</artifactId>
<version>5.1</version>
<exclusions>
<exclusion>
<artifactId>asm</artifactId>
<groupId>org.ow2.asm</groupId>
</exclusion>
</exclusions>
</dependency>
This is my solution without using any library or native javascript function.
function deepClone(obj) {
if (typeof obj !== "object") {
return obj;
} else {
let newObj =
typeof obj === "object" && obj.length !== undefined ? [] : {};
for (let key in obj) {
if (key) {
newObj[key] = deepClone(obj[key]);
}
}
return newObj;
}
}
If you've got many database it import and the dumps is big (I often work with multigigabyte Gzipped dumps).
There here a way to do it inside mysql.
$ mkdir databases
$ cd databases
$ scp user@orgin:*.sql.gz . # Here you would just use putty to copy into this dir.
$ mkfifo src
$ mysql -u root -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 1
Server version: 5.5.41-0
Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql> create database db1;
mysql> \! ( zcat db1.sql.gz > src & )
mysql> source src
.
.
mysql> create database db2;
mysql> \! ( zcat db2.sql.gz > src & )
mysql> source src
The only advantage this has over
zcat db1.sql.gz | mysql -u root -p
is that you can easily do multiple without enter the password lots of times.
It's easier using Array.filter
:
var unique = arr.filter(function(elem, index, self) {
return index === self.indexOf(elem);
})
I would recommend to use sftp, use this command sftp -oPort=7777 user@host
where -oPort is custom port number of ssh , in case if u changed it to 7777, then u can use -oPort, else if use only port 22 then plain sftp user@host
which asks for the password , then u can log in, and u can navigate to required location using cd /home/user
then a simple command get table
u can download it, If u want to download a directory/folder get -r someDirectory
will do it. If u want the file permissions also to exist then get -Pr someDirectory
.
For uploading on to remote change get to put in above commands.
As of 2015, you should use CSP2's frame-ancestors
directive for this. This is implemented via an HTTP response header.
e.g.
Content-Security-Policy: frame-ancestors 'none'
Of course, not many browsers support CSP2 yet so it is wise to include the old X-Frame-Options
header:
X-Frame-Options: DENY
I would advise to include both anyway, otherwise your site would continue to be vulnerable to Clickjacking attacks in old browsers, and of course you would get undesirable framing even without malicious intent. Most browsers do update automatically these days, however you still tend to get corporate users being stuck on old versions of Internet Explorer for legacy application compatibility reasons.
I know this question is 10 years old but there is no C# solution and this took me hours to figure out. I'm using the .NET driver and System.Linq
to return a list of the keys.
var map = new BsonJavaScript("function() { for (var key in this) { emit(key, null); } }");
var reduce = new BsonJavaScript("function(key, stuff) { return null; }");
var options = new MapReduceOptions<BsonDocument, BsonDocument>();
var result = await collection.MapReduceAsync(map, reduce, options);
var list = result.ToEnumerable().Select(item => item["_id"].ToString());
.button input,
.button a {
...
}
For some reason the android:textColor only seems to update the title color. You can change the message text color by using a
SpannableString.AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(this, R.style.MyDialogTheme));
AlertDialog dialog = builder.create();
Spannable wordtoSpan = new SpannableString("I know just how to whisper, And I know just how to cry,I know just where to find the answers");
wordtoSpan.setSpan(new ForegroundColorSpan(Color.BLUE), 15, 30, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
dialog.setMessage(wordtoSpan);
dialog.show();
Using Javascript
var elemDiv = document.createElement('div');
elemDiv.style.cssText = 'position:absolute;width:100%;height:100%;opacity:0.3;z-index:100;background:#000;';
document.body.appendChild(elemDiv);
Using jQuery
$('body').append('<div style="position:absolute;width:100%;height:100%;opacity:0.3;z-index:100;background:#000;"></div>');
// for numbers
a = [1,3,2,4,5,6,7,8, 1,1,4,5,6]
$.unique(a)
[7, 6, 1, 8, 3, 2, 5, 4]
// for string
a = ["a", "a", "b"]
$.unique(a)
["b", "a"]
And for dom elements there is no example is needed here I guess because you already know that!
Here is the jsfiddle link of live example: http://jsfiddle.net/3BtMc/4/
Here is an implementation of a single key to multi value map in C# which uses a set based key type:
https://github.com/ColmBhandal/CsharpExtras/blob/master/CsharpExtras/Dictionary/MultiValueMapImpl.cs
The dictionary behaves like a regular dictionary from the key type onto a set of the value type, but also provides functionality to directly add a single value of the value type, and in the background handles the creation of an underlying set and/or addition to that set.
If you wanted to remove the href, change the cursor and also prevent clicking on it, this should work:
$("a").attr('href', '').css({'cursor': 'pointer', 'pointer-events' : 'none'});
I've doing it with a function. In this case I will only transform character variables to factor:
for (i in 1:ncol(data)){
if(is.character(data[,i])){
data[,i]=factor(data[,i])
}
}
Another possible answer for Windows 10:
The command httpd -k restart
does not work on my machine somehow.
Try to use the Windows 10 Service to restart the relative service.
I found the issue that I never had before.
I just had to delete /etc/nginx/sites-available/default
. Then it worked.
This deletion will delete the symlink only, As backup you can find default file in
/etc/nginx/sites-enabled/default
My conf was in /etc/nginx/default
.
You may not want to add methods to the Array prototype, which may conflict with other libraries.
I've seen a lot of examples use forEach which, I wouldn't recommend for large arrays due to its poor performance vs a for loop. https://coderwall.com/p/kvzbpa/don-t-use-array-foreach-use-for-instead
Also Math.max(Math, [1,2,3]);
Always gives me NaN?
function minArray(a) {
var min=a[0]; for(var i=0,j=a.length;i<j;i++){min=a[i]<min?a[i]:min;}
return min;
}
function maxArray(a) {
var max=a[0]; for(var i=0,j=a.length;i<j;i++){max=a[i]>max?a[i]:max;}
return max;
}
minArray([1,2,3]); // returns 1
If you have an array of objects the minArray() function example below will accept 2 parameters, the first is the array and the second is the key name for the object key value to compare. The function in this case would return the index of the array that has the smallest given key value.
function minArray(a, key) {
var min, i, j, index=0;
if(!key) {
min=a[0];
for(i=0,j=a.length;i<j;i++){min=a[i]<min?a[i]:min;}
return min;
}
min=a[0][key];
for(i=0,j=a.length;i<j;i++){
if(a[i][key]<min) {
min = a[i][key];
index = i;
}
}
return index;
}
var a = [{fee: 9}, {fee: 2}, {fee: 5}];
minArray(a, "fee"); // returns 1, as 1 is the proper array index for the 2nd array element.
Jon Tan has done this with his site - http://jontangerine.com/ Everything including images has been declared in ems. Everything. This is how the desired effect is achieved. Text zoom and screen zoom yield almost the exact same result.
You can use AddHandler to add a handler for any event.
For example, this might be:
AddHandler theButton.Click, AddressOf Me.theButton_Click
Or you can do this way :
((TextView)findViewById(R.id.this_is_the_id_of_textview)).setText("Test");
What about this one :
<DockPanel Margin="8">
<Border CornerRadius="6" BorderBrush="Gray" Background="LightGray" BorderThickness="2" DockPanel.Dock="Top">
<StackPanel Orientation="Horizontal">
<TextBlock FontSize="14" Padding="0 0 8 0" HorizontalAlignment="Center" VerticalAlignment="Center">Search:</TextBlock>
<TextBox x:Name="txtSearchTerm" HorizontalAlignment="Center" VerticalAlignment="Center" />
<Image Source="lock.png" Width="32" Height="32" HorizontalAlignment="Center" VerticalAlignment="Center" />
</StackPanel>
</Border>
<StackPanel Orientation="Horizontal" DockPanel.Dock="Bottom" Height="25" />
</DockPanel>
I had simply changed the capitalization of ONE character in one of my report parameters and could no longer deploy. Changing the single character back to uppercase allowed me to redeploy. Remarkable.
This syntax has changed with the newer Apache HTTPd server, please see upgrade to apache 2.4 doc for full details.
2.2 configuration syntax was
Order deny,allow
Deny from all
2.4 configuration now is
Require all denied
Thus, this 2.2 syntax
order deny,allow
deny from all
allow from 127.0.0.1
Would ne now written
Require local
If you need to update the value in a particular table:
UPDATE TABLE-NAME SET COLUMN-NAME = REPLACE(TABLE-NAME.COLUMN-NAME, 'STRING-TO-REPLACE', 'REPLACEMENT-STRING');
where
TABLE-NAME - The name of the table being updated
COLUMN-NAME - The name of the column being updated
STRING-TO-REPLACE - The value to replace
REPLACEMENT-STRING - The replacement
You can think of an iframe as an embedded browser window that you can put on an HTML page to show another URL inside it. This URL can be totally distinct from your web site/app.
You can put an iframe in any HTML page, so you could put one inside a contentplaceholder in a webform that has a Masterpage and it will appear with whatever URL you load into it (via Javascript, or C# if you turn your iframe into a server-side control (runat='server'
) on the final HTML page that your webform produces when requested.
And you can load a URL into your iframe that is a .aspx
page.
But - iframes have nothing to do with the ASP.net mechanism. They are HTML elements that can be made to run server-side, but they are essentially 'dumb' and unmanaged/unconnected to the ASP.Net mechanisms - don't confuse a Contentplaceholder with an iframe.
Incidentally, the use of iframes is still contentious - do you really need to use one? Can you afford the negative trade-offs associated with them e.g. lack of navigation history ...?
with paging you need to do some calculation
int index = Convert.ToInt32(e.CommandArgument) % GridView1.PageSize;
Find missing all elements from array
int[] array = {3,5,7,8,2,1,32,5,7,9,30,5};
TreeMap<Integer, Integer> map = new TreeMap<>();
for(int i=0;i<array.length;i++) {
map.put(array[i], 1);
}
int maxSize = map.lastKey();
for(int j=0;j<maxSize;j++) {
if(null == map.get(j))
System.out.println("Missing `enter code here`No:"+j);
}
Simply use :
"SELECT * FROM `trees` WHERE LOWER(trees.`title`) LIKE '%elm%'";
Or Use
"SELECT * FROM `trees` WHERE LCASE(trees.`title`) LIKE '%elm%'";
Both functions works same
Set the display
property to inline
for the list you want this to apply to. There's a good explanation of displaying lists on A List Apart.
If you want to ALWAYS exclude certain properties for any class, you could use setMixInResolver
method:
@JsonIgnoreProperties({"id", "index", "version"})
abstract class MixIn {
}
mapper.setMixInResolver(new ClassIntrospector.MixInResolver(){
@Override
public Class<?> findMixInClassFor(Class<?> cls) {
return MixIn.class;
}
@Override
public ClassIntrospector.MixInResolver copy() {
return this;
}
});
Try this:-
File file = new File("contactids.txt");
Scanner scanner = new Scanner(file);
while(scanner.hasNextLong())
{
// Read values here like long input = scanner.nextLong();
}
The accepted answer here is correct but I'd like to add a little info. If you are using a library / framework like bootstrap there may be built in classes for this. For example bootstrap uses the text-right
class. Use it like this:
<input type="text" class="text-right"/>
<input type="number" class="text-right"/>
As a note this works on other input types as well, like numeric as shown above.
If you aren't using a nice framework like bootstrap then you can make your own version of this helper class. Similar to other answers but we are not going to add it directly to the input class so it won't apply to every single input on your site or page, this might not be desired behavior. So this would create a nice easy css class to align things right without needing inline styling or affecting every single input box.
.text-right{
text-align: right;
}
Now you can use this class exactly the same as the inputs above with class="text-right"
. I know it isn't saving that many key strokes but it makes your code cleaner.
You are using setTimeout
wrong way. The (one of) function signature is setTimeout(callback, delay)
. So you can easily specify what code should be run after what delay.
var codeAddress = (function() {
var index = 0;
var delay = 100;
function GeocodeCallback(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
new google.maps.Marker({ map: map, position: results[0].geometry.location, animation: google.maps.Animation.DROP });
console.log(results);
}
else alert("Geocode was not successful for the following reason: " + status);
};
return function(vPostCode) {
if (geocoder) setTimeout(geocoder.geocode.bind(geocoder, { 'address': "'" + vPostCode + "'"}, GeocodeCallback), index*delay);
index++;
};
})();
This way, every codeAddress()
call will result in geocoder.geocode()
being called 100ms later after previous call.
I also added animation to marker so you will have a nice animation effect with markers being added to map one after another. I'm not sure what is the current google limit, so you may need to increase the value of delay
variable.
Also, if you are each time geocoding the same addresses, you should instead save the results of geocode to your db and next time just use those (so you will save some traffic and your application will be a little bit quicker)
You could try this:
$in_str = 'this is a test';
$hex_ary = array();
foreach (str_split($in_str) as $chr) {
$hex_ary[] = sprintf("%02X", ord($chr));
}
echo implode(' ',$hex_ary);
This is the code that I've found to run the fastest so far. I ran it on 109015 byte arrays of length 32, in 23ms. I was running it on a VM so it'll probably run faster on bare metal.
public static final char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
public static char[] encodeHex( final byte[] data ){
final int l = data.length;
final char[] out = new char[l<<1];
for( int i=0,j=0; i<l; i++ ){
out[j++] = HEX_DIGITS[(0xF0 & data[i]) >>> 4];
out[j++] = HEX_DIGITS[0x0F & data[i]];
}
return out;
}
Then you can just do
String s = new String( encodeHex(myByteArray) );
I had a similar problem using view animations. So I've put an animation listener to make sure I'd wait for the animation to end before trying to request a keyboard access on the shown edittext.
bottomUp.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
if (textToFocus != null) {
// Position cursor at the end of the text
textToFocus.setSelection(textToFocus.getText().length());
// Show keyboard
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(textToFocus, InputMethodManager.SHOW_IMPLICIT);
}
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
I solved the same issue by removing:
compile fileTree(include: ['*.jar'], dir: 'libs')
and adding for each jar file:
compile files('libs/yourjarfile.jar')
Disconnected recordsets can be useful.
Const adVarChar = 200 'the SQL datatype is varchar
'Create a disconnected recordset
Set rs = CreateObject("ADODB.RECORDSET")
rs.Fields.append "SortField", adVarChar, 25
rs.CursorType = adOpenStatic
rs.Open
rs.AddNew "SortField", "Some data"
rs.Update
rs.AddNew "SortField", "All data"
rs.Update
rs.Sort = "SortField"
rs.MoveFirst
Do Until rs.EOF
strList=strList & vbCrLf & rs.Fields("SortField")
rs.MoveNext
Loop
MsgBox strList
I just had this problem of Chrome storing a Session ID but I do not like the idea of disabling the option to continue where I left off. I looked at the cookies for the website and found a Session ID cookie for the login page. Deleting that did not correct my problem. I search for the domain and found there was another Session ID cookie on the domain. Deleting both Session ID cookies manually fixed the problem and I did not close and reopen the browser which could have restored the cookies.
First, here's some sample data:
set.seed(1)
dat <- data.frame(one = rnorm(15),
two = sample(LETTERS, 15),
three = rnorm(15),
four = runif(15))
dat <- data.frame(lapply(dat, function(x) { x[sample(15, 5)] <- NA; x }))
head(dat)
# one two three four
# 1 NA M 0.80418951 0.8921983
# 2 0.1836433 O -0.05710677 NA
# 3 -0.8356286 L 0.50360797 0.3899895
# 4 NA E NA NA
# 5 0.3295078 S NA 0.9606180
# 6 -0.8204684 <NA> -1.28459935 0.4346595
Here's our replacement:
dat[["four"]][is.na(dat[["four"]])] <- 0
head(dat)
# one two three four
# 1 NA M 0.80418951 0.8921983
# 2 0.1836433 O -0.05710677 0.0000000
# 3 -0.8356286 L 0.50360797 0.3899895
# 4 NA E NA 0.0000000
# 5 0.3295078 S NA 0.9606180
# 6 -0.8204684 <NA> -1.28459935 0.4346595
Alternatively, you can, of course, write dat$four[is.na(dat$four)] <- 0
I'll just assume that gitk
is not desired for this. In that case, try git show --name-only <sha>
.
If you use maven and this piece of code is located in the main
folder, try relocating it to the test
folder.
While you can have a default page in the MVC project, the more conventional implementation for a default view would be to use a default controller, implememented in the global.asax, through the 'RegisterRoutes(...)' method. For instance if you wanted your Public\Home controller to be your default route/view, the code would be:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Public", action = "Home", id = UrlParameter.Optional } // Parameter defaults
);
}
For this to be functional, you are required to have have a set Start Page in the project.
I can't comment so here goes. About @David Storey answer.
Be careful on the "order of execution" in CSS3 chains! The order is right to left, not left to right.
transformation: translate(0,10%) rotate(25deg);
The rotate
operation is done first, then the translate
.
See: CSS3 transform order matters: rightmost operation first
When dividing your program code over multiple files, module.exports
is used to publish variables and functions to the consumer of a module. The require()
call in your source file is replaced with corresponding module.exports
loaded from the module.
Remember when writing modules
module.exports
object is also available as exports
shorthand. But when returning a sole function, always use module.exports
.According to: "Modules Part 2 - Writing modules".
To have the code within one line, try this:
startActivity(new Intent(Intent.ACTION_CALL, Uri.parse("tel:123456789")));
along with the proper manifest permission:
<uses-permission android:name="android.permission.CALL_PHONE"></uses-permission>
Hope this helps!
if you happened to use NLog in your ASP.net project, you can add a Debugger target:
<targets>
<target name="debugger" xsi:type="Debugger"
layout="${date:format=HH\:mm\:ss}|${pad:padding=5:inner=${level:uppercase=true}}|${message} "/>
and writes logs to this target for the levels you want:
<rules>
<logger name="*" minlevel="Trace" writeTo="debugger" />
now you have console output just like Jetty in "Output" window of VS, and make sure you are running in Debug Mode(F5).
Right now you seem to be saying 'does this array of strings equal this string', which of course it never would.
Perhaps you should think about iterating through your array of strings with a loop, and checking each to see if they are equals() with the inputted string?
...or do I misunderstand your question?
With CSS only? This is sort of possible on text inputs by using user-select:none
:
.print {
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
It's well worth noting that this will not work in browsers which do not support CSS3 or support the user-select
property. The readonly
property should be ideally given to the input markup you wish to be made readonly, but this does work as a hacky CSS alternative.
With JavaScript:
document.getElementById("myReadonlyInput").setAttribute("readonly", "true");
Edit: The CSS method no longer works in Chrome (29). The -webkit-user-select
property now appears to be ignored on input elements.
This is a circle shape with icon inside:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/ok_icon"/>
<item>
<shape
android:shape="oval">
<solid android:color="@color/transparent"/>
<stroke android:width="2dp" android:color="@color/button_grey"/>
</shape>
</item>
</layer-list>
If a class is declared as static then the variables and methods need to be declared as static.
A class can be declared static, indicating that it contains only static members. It is not possible to create instances of a static class using the new keyword. Static classes are loaded automatically by the .NET Framework common language runtime (CLR) when the program or namespace containing the class is loaded.
Use a static class to contain methods that are not associated with a particular object. For example, it is a common requirement to create a set of methods that do not act on instance data and are not associated to a specific object in your code. You could use a static class to hold those methods.
->The main features of a static class are:
Example
static class CollegeRegistration
{
//All static member variables
static int nCollegeId; //College Id will be same for all the students studying
static string sCollegeName; //Name will be same
static string sColegeAddress; //Address of the college will also same
//Member functions
public static int GetCollegeId()
{
nCollegeId = 100;
return (nCollegeID);
}
//similarly implementation of others also.
} //class end
public class student
{
int nRollNo;
string sName;
public GetRollNo()
{
nRollNo += 1;
return (nRollNo);
}
//similarly ....
public static void Main()
{
//Not required.
//CollegeRegistration objCollReg= new CollegeRegistration();
//<ClassName>.<MethodName>
int cid= CollegeRegistration.GetCollegeId();
string sname= CollegeRegistration.GetCollegeName();
} //Main end
}
If none the above work, then try this :
Modify the LISTENER.ora
(mine is found in : oracle\product\11.2.0\dbhome_1\NETWORK\ADMIN\listener.ora
) ==> add a custom listener that points to your database(SID), example my SID is XZ0301, so :
## Base XZ03001
SID_LIST_LISTENER_XZ03001=(SID_LIST=(SID_DESC=(ORACLE_HOME =
E:\oracle\product\11.2.0\dbhome_1)(SID_NAME= XZ03001)))
LISTENER_XZ03001=(DESCRIPTION_LIST=(ADDRESS=(PROTOCOL =
TCP)(HOST=MyComputerName)(PORT= 1521)))
DIAG_ADR_ENABLED_LISTENER_XZ03001=ON
ADR_BASE_LISTENER_XZ03001=E:\oracle
Restart your machine
For Windows 7, use the following to modify the LISTENER.ora: - Go to Start > All Programs > Accessories - Right click Notepad and then click Run as Administrator . - File>open and navigate to the tnsnames.ora file. - Make the changes then it should allow you to save
There is no difference (in SQL Server, at least). Both queries use the same execution plan.
http://sqlmag.com/database-performance-tuning/distinct-vs-group
Maybe there is a difference, if there are sub-queries involved:
There is no difference (Oracle-style):
http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:32961403234212
public int[] merge(int[] a, int[] b) {
int[] result = new int[a.length + b.length];
int aIndex, bIndex = 0;
for (int i = 0; i < result.length; i++) {
if (aIndex < a.length && bIndex < b.length) {
if (a[aIndex] < b[bIndex]) {
result[i] = a[aIndex];
aIndex++;
} else {
result[i] = b[bIndex];
bIndex++;
}
} else if (aIndex < a.length) {
result[i] = a[aIndex];
aIndex++;
} else {
result[i] = b[bIndex];
bIndex++;
}
}
return result;
}
If you use a JSONB field, you must convert it to JSON with .to_json (ROR)
Change
die (mysqli_error());
to
die('Error: ' . mysqli_error($myConnection));
in the query
$query = mysqli_query($myConnection, $sqlCommand) or die (mysqli_error());
I had this problem before and I made fallback way for loading. Basically first way work within .jar file and second way works within eclipse or other IDE.
public class MyClass {
public static InputStream accessFile() {
String resource = "my-file-located-in-resources.txt";
// this is the path within the jar file
InputStream input = MyClass.class.getResourceAsStream("/resources/" + resource);
if (input == null) {
// this is how we load file within editor (eg eclipse)
input = MyClass.class.getClassLoader().getResourceAsStream(resource);
}
return input;
}
}
May be you can see this Log extension class: https://github.com/dbauduin/Android-Tools/tree/master/logs.
It enables you to have a fine control on logs. You can for example disable all logs or just the logs of some packages or classes.
Moreover, it adds some useful functionalities (for instance you don't have to pass a tag for each log).
Give this a try...
server {
listen 80;
server_name dev.int.com;
access_log off;
location / {
proxy_pass http://IP:8080;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-for $remote_addr;
port_in_redirect off;
proxy_redirect http://IP:8080/jira /;
proxy_connect_timeout 300;
}
location ~ ^/stash {
proxy_pass http://IP:7990;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-for $remote_addr;
port_in_redirect off;
proxy_redirect http://IP:7990/ /stash;
proxy_connect_timeout 300;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/local/nginx/html;
}
}
Here's my simple solution to update the query params in the URL without refreshing the page. Make sure it works for your use case.
const query = { ...this.$route.query, someParam: 'some-value' };
this.$router.replace({ query });
Summarising @Rasmi Ranjan Nayak and @nogard answers and adding another option:
You should use the flag --gtest_filter
, like
--gtest_filter=Test_Cases1*
(You can also do this in Properties|Configuration Properties|Debugging|Command Arguments)
You should set the variable GTEST_FILTER
like
export GTEST_FILTER = "Test_Cases1*"
You should set a flag filter
, like
::testing::GTEST_FLAG(filter) = "Test_Cases1*";
such that your main function becomes something like
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
::testing::GTEST_FLAG(filter) = "Test_Cases1*";
return RUN_ALL_TESTS();
}
See section Running a Subset of the Tests for more info on the syntax of the string you can use.
just try to push it to your branch again. This will ask your username and password again, so you can feed in the changed password. So that your new password will be stored again in the cache.
An updated solution that gets you a list:
dataFrame.select("YOUR_COLUMN_NAME").map(r => r.getString(0)).collect.toList
Your format is not the expected ISO format, you should try
DateTimeFormatter format = DateTimeFormat.forPattern("dd/MM/yyyy HH:mm:ss");
DateTime time = format.parseDateTime("04/02/2011 20:27:05");
You need to first add using Microsoft.Win32;
to your code page.
Then you can begin to use the Registry
classes:
try
{
using (RegistryKey key = Registry.LocalMachine.OpenSubKey("Software\\Wow6432Node\\MySQL AB\\MySQL Connector\\Net"))
{
if (key != null)
{
Object o = key.GetValue("Version");
if (o != null)
{
Version version = new Version(o as String); //"as" because it's REG_SZ...otherwise ToString() might be safe(r)
//do what you like with version
}
}
}
}
catch (Exception ex) //just for demonstration...it's always best to handle specific exceptions
{
//react appropriately
}
BEWARE: unless you have administrator access, you are unlikely to be able to do much in LOCAL_MACHINE
. Sometimes even reading values can be a suspect operation without admin rights.
extension UITextField {
func setBottomBorder(color:String) {
self.borderStyle = UITextBorderStyle.None
let border = CALayer()
let width = CGFloat(1.0)
border.borderColor = UIColor(hexString: color)!.cgColor
border.frame = CGRect(x: 0, y: self.frame.size.height - width, width: self.frame.size.width, height: self.frame.size.height)
border.borderWidth = width
self.layer.addSublayer(border)
self.layer.masksToBounds = true
}
}
and then just do this:
yourTextField.setBottomBorder(color: "#3EFE46")
Although this may be more complicated/heavier-weight than you want, one very flexible way to do it is using something like Expect (or one of the derivatives in another programming language).
Expect is a language designed specifically to control text-based applications, which is exactly what you are looking to do. If you end up needing to do something more complicated (like with logic to actually decide what to do/answer next), Expect is the way to go.
On top of dhobbs answer above (https://stackoverflow.com/a/9728478/624597), here is an extra functionality of storing results to a file (I personally use it to copy and paste to FreeMind to have a nice overview of the structure, therefore I used tabs instead of spaces for indentation):
import os
def list_files(startpath):
with open("folder_structure.txt", "w") as f_output:
for root, dirs, files in os.walk(startpath):
level = root.replace(startpath, '').count(os.sep)
indent = '\t' * 1 * (level)
output_string = '{}{}/'.format(indent, os.path.basename(root))
print(output_string)
f_output.write(output_string + '\n')
subindent = '\t' * 1 * (level + 1)
for f in files:
output_string = '{}{}'.format(subindent, f)
print(output_string)
f_output.write(output_string + '\n')
list_files(".")
Something like this works fine for me:
public partial class Form1 : Form
{
Form mainFormHandler;
...
}
private void Form1_Load(object sender, EventArgs e){
mainFormHandler = Application.OpenForms[0];
//or instead use this one:
//mainFormHandler = Application.OpenForms["Form1"];
}
Then you can change the size as below:
mainFormHandler.Width = 600;
mainFormHandler.Height= 400;
or
mainFormHandler.Size = new Size(600, 400);
Another useful point is that if you want to change the size of mainForm
from another Form
, you can simply use Property to set the size.
My codegolfing coworker came up with this (ES6), inclusive:
(s,f)=>[...Array(f-s+1)].map((e,i)=>i+s)
non inclusive:
(s,f)=>[...Array(f-s)].map((e,i)=>i+s)
Encrypt:
openssl enc -in infile.txt -out encrypted.dat -e -aes256 -k symmetrickey
Decrypt:
openssl enc -in encrypted.dat -out outfile.txt -d -aes256 -k symmetrickey
For details, see the openssl(1)
docs.
I came up with an generic, interesting solution to this problem:
class SafeInvocator(object):
def __init__(self, module):
self._module = module
def _safe(self, func):
def inner(*args, **kwargs):
try:
return func(*args, **kwargs)
except:
return None
return inner
def __getattr__(self, item):
obj = getattr(self.module, item)
return self._safe(obj) if hasattr(obj, '__call__') else obj
and you can use it like so:
safe_json = SafeInvocator(json)
text = "{'foo':'bar'}"
item = safe_json.loads(text)
if item:
# do something
For this use below code in your app gradle file under android closure.
dexOptions { javaMaxHeapSize "4g" }
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/activity_register_header"
android:minHeight="50dp"
android:orientation="vertical"
android:visibility="gone" />
Try this piece of code..For me this code worked..
Even better!
long tStart = System.nanoTime();
long tEnd = System.nanoTime();
long tRes = tEnd - tStart; // time in nanoseconds
Read the documentation about nanoTime()!
$("#btnId").click(function(e){
e.preventDefault();
$.ajax({
...
beforeSend : function(xhr, opts){
//show loading gif
},
success: function(){
},
complete : function() {
//remove loading gif
}
});
});
String Declaration:
String str;
String Initialization
String[] str=new String[3];//if we give string[2] will get Exception insted
str[0]="Tej";
str[1]="Good";
str[2]="Girl";
String str="SSN";
We can get individual character in String:
char chr=str.charAt(0);`//output will be S`
If I want to to get individual character Ascii value like this:
System.out.println((int)chr); //output:83
Now i want to convert Ascii value into Charecter/Symbol.
int n=(int)chr;
System.out.println((char)n);//output:S
C++11 has some portable timer stuff. Check out sleep_for.
From Tools > Preferences > Database > NLS Parameter and set Date Format as
DD-MON-RR HH:MI:SS
A simple tkinter code for Python 3 for setting background image .
from tkinter import *
from tkinter import messagebox
top = Tk()
C = Canvas(top, bg="blue", height=250, width=300)
filename = PhotoImage(file = "C:\\Users\\location\\imageName.png")
background_label = Label(top, image=filename)
background_label.place(x=0, y=0, relwidth=1, relheight=1)
C.pack()
top.mainloop
jstat -gccapacity javapid (ex. stat -gccapacity 28745)
jstat -gccapacity javapid gaps frames (ex. stat -gccapacity 28745 550 10 )
Sample O/P of above command
NGCMN NGCMX NGC S0C
87040.0 1397760.0 1327616.0 107520.0
NGCMN Minimum new generation capacity (KB).
NGCMX Maximum new generation capacity (KB).
NGC Current new generation capacity (KB).
Get more details about this at http://docs.oracle.com/javase/1.5.0/docs/tooldocs/share/jstat.html
The approach
for item in all:
item.start()
is simple, easy, readable, and concise. This is the main approach Python provides for this operation. You can certainly encapsulate it in a function if that helps something. Defining a special function for this for general use is likely to be less clear than just writing out the for loop.
You can use Column.isNull
/ Column.isNotNull
:
df.where(col("dt_mvmt").isNull())
df.where(col("dt_mvmt").isNotNull())
If you want to simply drop NULL
values you can use na.drop
with subset
argument:
df.na.drop(subset=["dt_mvmt"])
Equality based comparisons with NULL
won't work because in SQL NULL
is undefined so any attempt to compare it with another value returns NULL
:
sqlContext.sql("SELECT NULL = NULL").show()
## +-------------+
## |(NULL = NULL)|
## +-------------+
## | null|
## +-------------+
sqlContext.sql("SELECT NULL != NULL").show()
## +-------------------+
## |(NOT (NULL = NULL))|
## +-------------------+
## | null|
## +-------------------+
The only valid method to compare value with NULL
is IS
/ IS NOT
which are equivalent to the isNull
/ isNotNull
method calls.
In Java, an Array stores its length separately from the structure that actually holds the data. When you create an Array, you specify its length, and that becomes a defining attribute of the Array. No matter what you do to an Array of length N (change values, null things out, etc.), it will always be an Array of length N.
A String's length is incidental; it is not an attribute of the String, but a byproduct. Though Java Strings are in fact immutable, if it were possible to change their contents, you could change their length. Knocking off the last character (if it were possible) would lower the length.
I understand this is a fine distinction, and I may get voted down for it, but it's true. If I make an Array of length 4, that length of four is a defining characteristic of the Array, and is true regardless of what is held within. If I make a String that contains "dogs", that String is length 4 because it happens to contain four characters.
I see this as justification for doing one with an attribute and the other with a method. In truth, it may just be an unintentional inconsistency, but it's always made sense to me, and this is always how I've thought about it.
Try replacing this
var query = context.Search(id, searchText);
with
var query = context.Search(id, searchText).tolist();
and everything will work well.
hmm. I have never used VB.net in any depth, so I'm making an assumption here, but I think the 'using' block might be close to what you want.
using defines a block scope for a variable, see the example below
using ( int temp = someFunction(param1) ) {
temp++; // this works fine
}
temp++; // this blows up as temp is out of scope here and has been disposed
Here is an article from Microsoft that explains a bit more
EDIT: yeah, this answer is wrong - the original assumption was incorrect. VB's 'WITH' is more like the new C# object initialisers:
var yourVariable = new yourObject { param1 = 20, param2 = "some string" };
Be Careful: If your app is targeting iPhone device only, iPad running with iphone compatible mode will return false for below statement:
#define IPAD UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad
The right way to detect physical iPad device is:
#define IS_IPAD_DEVICE ([(NSString *)[UIDevice currentDevice].model hasPrefix:@"iPad"])
You can apply any one approach:
$("#Input_Id").change(function(){ // 1st
// do your code here
// When your element is already rendered
});
$("#Input_Id").on('change', function(){ // 2nd (A)
// do your code here
// It will specifically called on change of your element
});
$("body").on('change', '#Input_Id', function(){ // 2nd (B)
// do your code here
// It will filter the element "Input_Id" from the "body" and apply "onChange effect" on it
});
The #!
line tells the kernel (specifically, the implementation of the execve
system call) that this program is written in an interpreted language; the absolute pathname that follows identifies the interpreter. Programs compiled to machine code begin with a different byte sequence -- on most modern Unixes, 7f 45 4c 46
(^?ELF) that identifies them as such.
You can put an absolute path to any program you want after the #!
, as long as that program is not itself a #!
script. The kernel rewrites an invocation of
./script arg1 arg2 arg3 ...
where ./script
starts with, say, #! /usr/bin/perl
, as if the command line had actually been
/usr/bin/perl ./script arg1 arg2 arg3
Or, as you have seen, you can use #! /bin/sh
to write a script intended to be interpreted by sh
.
The #!
line is only processed if you directly invoke the script (./script
on the command line); the file must also be executable (chmod +x script
). If you do sh ./script
the #!
line is not necessary (and will be ignored if present), and the file does not have to be executable. The point of the feature is to allow you to directly invoke interpreted-language programs without having to know what language they are written in. (Do grep '^#!' /usr/bin/*
-- you will discover that a great many stock programs are in fact using this feature.)
Here are some rules for using this feature:
#!
must be the very first two bytes in the file. In particular, the file must be in an ASCII-compatible encoding (e.g. UTF-8 will work, but UTF-16 won't) and must not start with a "byte order mark", or the kernel will not recognize it as a #!
script.#!
must be an absolute path (starts with /
). It cannot contain space, tab, or newline characters.#!
and the /
. Do not put more than one space there.#!
line, they will not be expanded.#! /usr/bin/awk -f
), sometimes it's just useful (#! /usr/bin/perl -Tw
). Unfortunately, you cannot put two or more arguments after the absolute path.#! /usr/bin/env interpreter
instead of #! /absolute/path/to/interpreter
. This is almost always a mistake. It makes your program's behavior depend on the $PATH
variable of the user who invokes the script. And not all systems have env
in the first place.setuid
or setgid
privileges can't use #!
; they have to be compiled to machine code. (If you don't know what setuid
is, don't worry about this.)Regarding csh
, it relates to sh
roughly as Nutrimat Advanced Tea Substitute does to tea. It has (or rather had; modern implementations of sh
have caught up) a number of advantages over sh
for interactive usage, but using it (or its descendant tcsh
) for scripting is almost always a mistake. If you're new to shell scripting in general, I strongly recommend you ignore it and focus on sh
. If you are using a csh
relative as your login shell, switch to bash
or zsh
, so that the interactive command language will be the same as the scripting language you're learning.
It is how to save results to CSV on the client-side without additional non-standard tools.
This example uses only mysql
client and awk
.
One-line:
mysql --skip-column-names --batch -e 'select * from dump3' t | awk -F'\t' '{ sep=""; for(i = 1; i <= NF; i++) { gsub(/\\t/,"\t",$i); gsub(/\\n/,"\n",$i); gsub(/\\\\/,"\\",$i); gsub(/"/,"\"\"",$i); printf sep"\""$i"\""; sep=","; if(i==NF){printf"\n"}}}'
Logical explanation of what is needed to do
First, let see how data looks like in RAW mode (with --raw
option). the database and table are respectively t
and dump3
You can see the field starting from "new line" (in the first row) is splitted into three lines due to new lines placed in the value.
mysql --skip-column-names --batch --raw -e 'select * from dump3' t one line 2 new line quotation marks " backslash \ two quotation marks "" two backslashes \\ two tabs new line the end of field another line 1 another line description without any special chars
--raw
option) - each record changed to the one-line texts by escaping characters like \
<tab>
and new-lines
mysql --skip-column-names --batch -e 'select * from dump3' t one line 2 new line\nquotation marks " backslash \\ two quotation marks "" two backslashes \\\\ two tabs\t\tnew line\nthe end of field another line 1 another line description without any special chars
The clue is to save data in CSV format with escaped characters.
The way to do that is to convert special entities which mysql --batch
produces (\t
as tabs \\
as backshlash and \n
as newline) into equivalent bytes for each value (field).
Then whole value is escaped by "
and enclosed also by "
.
Btw - using the same characters for escaping and enclosing gently simplifies output and processing, because you don't have two special characters.
For this reason all you have to do with values (from csv format perspective) is to change "
to ""
whithin values. In more common way (with escaping and enclosing respectively \
and "
) you would have to first change \
to \\
and then change "
into \"
.
And the commands' explanation step by step:
# we produce one-line output as showed in step 2. mysql --skip-column-names --batch -e 'select * from dump3' t # set fields separator to because mysql produces in that way | awk -F'\t' # this start iterating every line/record from the mysql data - standard behaviour of awk '{ # field separator is empty because we don't print a separator before the first output field sep=""; -- iterating by every field and converting the field to csv proper value for(i = 1; i <= NF; i++) { -- note: \\ two shlashes below mean \ for awk because they're escaped -- changing \t into byte corresponding to <tab> gsub(/\\t/, "\t",$i); -- changing \n into byte corresponding to new line gsub(/\\n/, "\n",$i); -- changing two \\ into one \ gsub(/\\\\/,"\\",$i); -- changing value into CSV proper one literally - change " into "" gsub(/"/, "\"\"",$i); -- print output field enclosed by " and adding separator before printf sep"\""$i"\""; -- separator is set after first field is processed - because earlier we don't need it sep=","; -- adding new line after the last field processed - so this indicates csv record separator if(i==NF) {printf"\n"} } }'
Copy conditionally formatted cells into Word (using CTRL+C, CTRL+V). Copy them back into Excel, keeping the source formatting. Now the conditional formatting is lost but you still have the colors and can check the RGB choosing Home > Fill color (or Font color) > More colors.
In order to complete this thread, I would suggest you to look into:
This is a library that helps with tons of javascript visualizations. However the learning curve is quite steep.
A library that makes it easy to create some d3.js visualizations (with limitations, of course).
DML (Data Manipulation Language) commands need to be commited/rolled back. Here is a list of those commands.
Data Manipulation Language (DML) statements are used for managing data within schema objects. Some examples:
INSERT - insert data into a table
UPDATE - updates existing data within a table
DELETE - deletes records from a table, the space for the records remain
MERGE - UPSERT operation (insert or update)
CALL - call a PL/SQL or Java subprogram
EXPLAIN PLAN - explain access path to data
LOCK TABLE - control concurrency
Based on your own answer, I'm guessing that your column has data formatted like this:
'DD/MM/YYYY HH:MI:SS'
The actual separators between Day/Month/Year don't matter, nor does anything that comes after the year.
You don't say what version of DB2 you are using or what platform it's running on, so I'm going to assume that it's on Linux, UNIX or Windows.
Almost any recent version of DB2 for Linux/UNIX/Windows (8.2 or later, possibly even older versions), you can do this using the TRANSLATE
function:
select
date(translate('GHIJ-DE-AB',column_with_date,'ABCDEFGHIJ'))
from
yourtable
With this solution it doesn't matter what comes after the date in your column.
In DB2 9.7, you can also use the TO_DATE
function (similar to Oracle's TO_DATE):
date(to_date(column_with_date,'DD-MM-YYYY HH:MI:SS'))
This requires your data match the formatting string; it's easier to understand when looking at it, but not as flexible as the TRANSLATE option.
To send data via Post methode with $http
of angularjs you need to change
data: "message=" + message
, with data: $.param({message:message})
<script>
in the <head>
, as that is dictated by the formats. However, some put javascript <script>
s at the bottom of the body, so that the page content will load without waiting for the <script>
, but this is a tradeoff since script execution will be delayed until other resources have loaded.For completely silencing the output, here what works for me
```{r error=FALSE, warning=FALSE, message=FALSE}
invisible({capture.output({
# Your code here
2 * 2
# etc etc
})})
```
The 5 measures used above are
error = FALSE
warning = FALSE
message = FALSE
invisible()
capture.output()
It's a trade off !
pros of each one :
CASE
isn't used for flow control... for this, you would need to use IF
...
But, there's a set-based solution to this problem instead of the procedural approach:
UPDATE tblEmployee
SET
InOffice = CASE WHEN @NewStatus = 'InOffice' THEN -1 ELSE InOffice END,
OutOffice = CASE WHEN @NewStatus = 'OutOffice' THEN -1 ELSE OutOffice END,
Home = CASE WHEN @NewStatus = 'Home' THEN -1 ELSE Home END
WHERE EmpID = @EmpID
Note that the ELSE
will preserves the original value if the @NewStatus
condition isn't met.
For me the solution was to correct the PATH
variable. It had Anaconda3\Library\bin as one of the first paths. This directory contains some Qt libraries, but not all. Apparently, that is a problem. Moving C:\Programs\Qt\5.12.3\msvc2017_64\bin to the front of PATH
solved the problem for me.
And if you would like to use an existing context, rather than a new context which would be loaded from xml configuration by org.springframework.web.context.ContextLoaderListener, then see -> https://stackoverflow.com/a/40694787/3004747
What about element.tagName
?
See also tagName
docs on MDN.
Also, Make sure that you are doing command Cntrl+C in the same terminal (tab) which is used to start the server.
In my case, I had 2 tabs but i forgot to stop the server from correct tab and i was wondering why Cntrl+C is not working.
For 100% viewport height use:
overflow: auto;
max-height: 100vh;
If you have an text/textarea attribute named my_attr you can get it by:
product->getMyAttr();
<img src='someimage.gif' id="datepicker" />
<input type="hidden" id="dp" />
$(document).on("click", "#datepicker", function () {
$("#dp").datepicker({
dateFormat: 'dd-mm-yy',
minDate: 'today'}).datepicker( "show" );
});
you just add this code for image clicking or any other html tag clicking event. This is done by initiate the datepicker function when we click the trigger.
I had the same problem too, but I found a solution.
from tkinter import *
# must add
root = Tk()
root.title("Calculator")
root.iconbitmap(r"image/icon.ico")
root.mainloop()
In the example, what python needed is an icon file, so when you dowload an icon as .png
it won't work cause it needs an .ico
file. So you need to find converters to convert your icon from png
to ico
.
you can try with
document.getElementById('btn').disabled = !this.checked"
<input type="submit" name="btn" id="btn" value="submit" disabled/>_x000D_
_x000D_
<input type="checkbox" onchange="document.getElementById('btn').disabled = !this.checked"/>
_x000D_
Assume the date as milliseconds date is 1526813885836
, so you can access the date as string with this sample code:
console.log(new Date(1526813885836).toString());
For clearness see below code:
const theTime = new Date(1526813885836);
console.log(theTime.toString());
You should be able to use the /quiet
or /qn
options with msiexec
to perform a silent install.
MSI packages export public properties, which you can set with the PROPERTY=value
syntax on the end of the msiexec
parameters.
For example, this command installs a package with no UI and no reboot, with a log and two properties:
msiexec /i c:\path\to\package.msi /quiet /qn /norestart /log c:\path\to\install.log PROPERTY1=value1 PROPERTY2=value2
You can read the options for msiexec
by just running it with no options from Start -> Run.