I got this error when attempting to build with Xcode 10. It appears to be a bug in the Swift compiler. Building with Whole Module Optimization
on, resolves the issue: https://forums.swift.org/t/illegal-instruction-4-when-trying-to-compile-project/16118
This is not an ideal solution, I will continue to use Xcode 9.4.1 until this issue is resolved.
I had the same problem. Firefox showed me this error but in chrome everything was OK. then after a google search, i used google cdn for jquery in index.html instead of loading local js file and the problem solved.
*NgIf can create problem here , so either use display none css or easier way is to Use [hidden]="!condition"
This is really just an expansion of BBB's answer which lead to to get my experiment working.
This script will simply create a file /tmp/testfile when you click on the button that says "Open Script".
This requires 3 files.
The File Tree:
root@test:/var/www/html# tree testscript/
testscript/
+-- index.html
+-- testexec.php
+-- test.sh
1. The main WebPage:
root@test:/var/www/html# cat testscript/index.html
<form action="/testscript/testexec.php">
<input type="submit" value="Open Script">
</form>
2. The PHP Page that runs the script and redirects back to the main page:
root@test:/var/www/html# cat testscript/testexec.php
<?php
shell_exec("/var/www/html/testscript/test.sh");
header('Location: http://192.168.1.222/testscript/index.html?success=true');
?>
3. The Script :
root@test:/var/www/html# cat testscript/test.sh
#!/bin/bash
touch /tmp/testfile
import math
import time
def check_prime(n):
if n == 1:
return False
if n == 2:
return True
if n % 2 == 0:
return False
from_i = 3
to_i = math.sqrt(n) + 1
for i in range(from_i, int(to_i), 2):
if n % i == 0:
return False
return True
Per the comments to the original post, merges / joins are well-suited for this problem. In particular, an inner join will return only values that are present in both dataframes, making thesetdiff
statement unnecessary.
Using the data from Dinre's example:
In base R:
cleanedA <- merge(data_A, data_B[, "index"], by = 1, sort = FALSE)
cleanedB <- merge(data_B, data_A[, "index"], by = 1, sort = FALSE)
Using the dplyr package:
library(dplyr)
cleanedA <- inner_join(data_A, data_B %>% select(index))
cleanedB <- inner_join(data_B, data_A %>% select(index))
To keep the data as two separate tables, each containing only its own variables, this subsets the unwanted table to only its index variable before joining. Then no new variables are added to the resulting table.
By POST file uploads are done (commonly, there are also other methods). Look into the method attribute of the form which contains the file-upload field ;)
The lowest limit of any related setting supersedes a higher setting:
See Handling file uploads: Common Pitfals which explains this in detail and how to calculate the values.
That looks more explicit for me:
int? id = outputIdParam.Value is DbNull ? default(int?) : outputIdParam.Value;
Try Making the Child Form's StartPosition Property set to Center Parent. This you can select from the form Properties.
Late to the party. But this might be helpful for someone.
All you need is your script and django-extensions
installed.
Just run the shell_plus
available in django_extensions
and import the script that you've written.
If your script is scpt.py
and it's inside a folder fol
you can run the script as follows.
python manage.py shell_plus
and just import your script inside the shell as follows.
>>> from fol import scpt
Use an object, as people are saying. However, note that you can not have integer keys. JavaScript will convert the integer to a string. The following outputs 20, not undefined:
var test = {}
test[2300] = 20;
console.log(test["2300"]);
Actually you don't need "install" or "compile" anything before using Boost in your project. You can just download and extract the Boost library to any location on your machine, which is usually like /usr/local/
.
When you compile your code, you can just indicate the compiler where to find the libraries by -I
. For example, g++ -I /usr/local/boost_1_59_0 xxx.hpp
.
private void StudentForm_Load(object sender, EventArgs e)
{
string q = @"SELECT [BatchID] FROM [Batch]"; //BatchID column name of Batch table
SqlDataReader reader = DB.Query(q);
while (reader.Read())
{
cbsb.Items.Add(reader["BatchID"].ToString()); //cbsb is the combobox name
}
}
My solution is to use m4. It's supported on most platforms and is included in the binutils package.
First include a macro changequote()
in the file to change the quoting characters to what you prefer (default is `'). The macro is removed when the file is processed.
changequote(`{{', `}}')
include({{other_file}})
On the commandline:
m4 -I./dir_containing_other_file/ input.md > _tmp.md
pandoc -o output.html _tmp.md
In Python 3,
urllib2
was replaced by two in-built modules namedurllib.request
andurllib.error
Adapted from source
So replace this:
import urllib2
With this:
import urllib.request as urllib2
You can even set a separate right margin for HTML. Under the specified path:
File >> Settings >> Editor >> Code Style >> HTML >> Other Tab >> Right margin (columns)
This is very useful because generally HTML and JS may be usually long in one line than Python. :)
Change as per below
@font-face {
font-family: "Futura";
src: url("../fonts/Futura_Medium_BT.eot"); /* IE */
src: local("Futura"), url( "../fonts/Futura_Medium_BT.ttf" ) format("truetype"); /* non-IE */
}
body nav {
font-family: "Futura";
font-size:1.2em;
height: 40px;
}
.process-list:after{
content: "\2191";
position: absolute;
top:50%;
right:-8px;
background-color: #ea1f41;
width:35px;
height: 35px;
border:2px solid #ffffff;
border-radius: 5px;
color: #ffffff;
z-index: 10000;
-webkit-transform: rotate(50deg) translateY(-50%);
-moz-transform: rotate(50deg) translateY(-50%);
-ms-transform: rotate(50deg) translateY(-50%);
-o-transform: rotate(50deg) translateY(-50%);
transform: rotate(50deg) translateY(-50%);
}
you can check this code . i hope you will easily understand.
A way to solve this without needing to use a FileSystemResource that requires a file on disk, is to use a ByteArrayResource, that way you can send a byte array in your post (this code works with Spring 3.2.3):
MultiValueMap<String, Object> map = new LinkedMultiValueMap<String, Object>();
final String filename="somefile.txt";
map.add("name", filename);
map.add("filename", filename);
ByteArrayResource contentsAsResource = new ByteArrayResource(content.getBytes("UTF-8")){
@Override
public String getFilename(){
return filename;
}
};
map.add("file", contentsAsResource);
String result = restTemplate.postForObject(urlForFacade, map, String.class);
I override the getFilename of the ByteArrayResource because if I don't I get a null pointer exception (apparently it depends on whether the java activation .jar is on the classpath, if it is, it will use the file name to try to determine the content type)
FileAppender appender = repository.GetAppenders().OfType<FileAppender>().FirstOrDefault();
if (appender != null)
logger.DebugFormat("log file located at : {0}", appender.File);
else
logger.Error("Could not locate fileAppender");
Use the command "vbNewLine"
Example
Hello & vbNewLine & "World"
will show up as Hello on one line and World on another
Template driven method
#receiverInput="ngModel" (blur)="receiverInput.control.setValue('')"
Using the syntax text_element.selectionStart
we can get the starting position of the selection of a text in terms of the index of the first character of the selected text in the text_element.value
and in case we want to get the same of the last character in the selection we have to use text_element.selectionEnd
.
Use it as follows:
<input type=text id=t1 value=abcd>
<button onclick="alert(document.getElementById('t1').selectionStart)">check position</button>
I'm giving you the fiddle_demo
Here's a simple single line alternative for users who don't have the watch
command who want to execute a command every 3 seconds:
while :; do your-command; sleep 3; done
It's an infinite loop that is basically the same as doing the following:
watch -n3 your-command
Didn't see an answer using tag helpers (Core MVC), so here it goes (for a delete action):
On HTML:
<form action="" method="post" role="form">
<table>
@for (var i = 0; i < Model.List.Count(); i++)
{
<tr>
<td>@Model.List[i].ItemDescription</td>
<td>
<input type="submit" value="REMOVE" class="btn btn-xs btn-danger"
asp-controller="ControllerName" asp-action="delete" asp-route-idForDeleteItem="@Model.List[i].idForDeleteItem" />
</td>
</tr>
}
</table>
</form>
On Controller:
[HttpPost("[action]/{idForDeleteItem}"), ActionName("Delete")]
public async Task<IActionResult> DeleteConfirmed(long idForDeleteItem)
{
///delete with param id goes here
}
Don't forget to use [Route("[controller]")]
BEFORE the class declaration - on controller.
If you are on a Mac or BSD or something else without the --date option, you can use:
date -r `expr \`date +%s\` - 86400` '+%a %d/%m/%Y'
Update: or perhaps...
date -r $((`date +%s` - 86400)) '+%a %d/%m/%Y'
If you're using MySQL, there is a method REGEXP that you can use...
http://dev.mysql.com/doc/refman/5.1/en/regexp.html#operator_regexp
So then you would use:
SELECT * FROM `shirts` WHERE `colors` REGEXP '\b1\b'
Here is an ES2017+ way to get the counts for all array items in O(N):
const arr = [1, 2, 3, 5, 2, 8, 9, 2];
const counts = {};
arr.forEach((el) => {
counts[el] = counts[el] ? (counts[el] += 1) : 1;
});
You can also optionally sort the output:
const countsSorted = Object.entries(counts).sort(([_, a], [__, b]) => a - b);
console.log(countsSorted) for your example array:
[
[ '2', 3 ],
[ '1', 1 ],
[ '3', 1 ],
[ '5', 1 ],
[ '8', 1 ],
[ '9', 1 ]
]
In my experience there are two places where we want to use uint8_t to mean 8 bits (and uint16_t, etc) and where we can have fields smaller than 8 bits. Both places are where space matters and we often need to look at a raw dump of the data when debugging and need to be able to quickly determine what it represents.
The first is in RF protocols, especially in narrow-band systems. In this environment we may need to pack as much information as we can into a single message. The second is in flash storage where we may have very limited space (such as in embedded systems). In both cases we can use a packed data structure in which the compiler will take care of the packing and unpacking for us:
#pragma pack(1)
typedef struct {
uint8_t flag1:1;
uint8_t flag2:1;
padding1 reserved:6; /* not necessary but makes this struct more readable */
uint32_t sequence_no;
uint8_t data[8];
uint32_t crc32;
} s_mypacket __attribute__((packed));
#pragma pack()
Which method you use depends on your compiler. You may also need to support several different compilers with the same header files. This happens in embedded systems where devices and servers can be completely different - for example you may have an ARM device that communicates with an x86 Linux server.
There are a few caveats with using packed structures. The biggest gotcha is that you must avoid dereferencing the address of a member. On systems with mutibyte aligned words, this can result in a misaligned exception - and a coredump.
Some folks will also worry about performance and argue that using these packed structures will slow down your system. It is true that, behind the scenes, the compiler adds code to access the unaligned data members. You can see that by looking at the assembly code in your IDE.
But since packed structures are most useful for communication and data storage then the data can be extracted into a non-packed representation when working with it in memory. Normally we do not need to be working with the entire data packet in memory anyway.
Here is some relevant discussion:
pragma pack(1) nor __attribute__ ((aligned (1))) works
Is gcc's __attribute__((packed)) / #pragma pack unsafe?
http://solidsmoke.blogspot.ca/2010/07/woes-of-structure-packing-pragma-pack.html
Well I always use the same easy way and it works for me. In your HTML keep the type as text (like this):
<input type="text" class="textfield" value="" id="onlyNumbers" name="onlyNumbers" onkeypress="return isNumber(event)" onpaste="return false;"/>
After this you only need to add a method on javascript
<script type="text/javascript">
function isNumber(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if ( (charCode > 31 && charCode < 48) || charCode > 57) {
return false;
}
return true;
}
</script>
With this easy validation you will only get positive numbers as you wanted. You can modify the charCodes to add more valid keys to your method.
Here´s the code working: Only numbers validation
For an incoming request like /v1/location/1234
, as you can imagine it would be difficult for Web API to automatically figure out if the value of the segment corresponding to '1234' is related to appid
and not to deviceid
.
I think you should change your route template to be like
[Route("v1/location/{deviceOrAppid?}", Name = "AddNewLocation")]
and then parse the deiveOrAppid
to figure out the type of id.
Also you need to make the segments in the route template itself optional otherwise the segments are considered as required. Note the ?
character in this case.
For example:
[Route("v1/location/{deviceOrAppid?}", Name = "AddNewLocation")]
This is mental. Use the scale-down property - it explains itself.
Inline styling:
<img src='/nic-cage.png' style={{ maxWidth: '50%', objectFit: 'scale-down' }} />
This will stop flex from stretching it. In this case, the image would go to 50% of the width of its parent container and the height would scale down to match.
Keep it simple.
From the update 2 and after narrowing down the problem scope, we can easily find that there is a brace missing at the end of the function addWord
. The compiler will never explicitly identify such a syntax error. instead, it will assume that the missing function definition located in some other object file. The linker will complain about it and hence directly will be categorized under one of the broad the error phrases which is identifier is undefined
. Reasonably, because with the current syntax the next function definition (in this case is ac_search
) will be included under the addWord
scope. Hence, it is not a global function anymore. And that is why compiler will not see this function outside addWord
and will throw this error message stating that there is no such a function. A very good elaboration about the compiler and the linker can be found in this article
I would like to add one very important comment: -
Many corporations deploy "internal use only" websites which are, effectively, "corporate applications" that happen to have been implemented through URLs. These URLs can (supposedly ...) only be resolved within "the company's internal network." (Which network magically includes all VPN-connected 'road warriors.')
When a user is dutifully-connected to the aforesaid network, their identity ("authentication") is [already ...] "conclusively known," as is their permission ("authorization") to do certain things ... such as ... "to access this website."
This "authentication + authorization" service can be provided by several different technologies, such as LDAP (Microsoft OpenDirectory), or Kerberos.
From your point-of-view, you simply know this: that anyone who legitimately winds-up at your website must be accompanied by [an environment-variable magically containing ...] a "token." (i.e. The absence of such a token must be immediate grounds for 404 Not Found
.)
The token's value makes no sense to you, but, should the need arise, "appropriate means exist" by which your website can "[authoritatively] ask someone who knows (LDAP... etc.)" about any and every(!) question that you may have. In other words, you do not avail yourself of any "home-grown logic." Instead, you inquire of The Authority and implicitly trust its verdict.
Uh huh ... it's quite a mental-switch from the "wild-and-wooly Internet."
You can do it in two ways, choose what suits your requirement:
Method I.) Replacing using line number. You can use built-in function enumerate()
in this case:
First, in read mode get all data in a variable
with open("your_file.txt",'r') as f:
get_all=f.readlines()
Second, write to the file (where enumerate comes to action)
with open("your_file.txt",'w') as f:
for i,line in enumerate(get_all,1): ## STARTS THE NUMBERING FROM 1 (by default it begins with 0)
if i == 2: ## OVERWRITES line:2
f.writelines("Mage\n")
else:
f.writelines(line)
Method II.) Using the keyword you want to replace:
Open file in read mode and copy the contents to a list
with open("some_file.txt","r") as f:
newline=[]
for word in f.readlines():
newline.append(word.replace("Warrior","Mage")) ## Replace the keyword while you copy.
"Warrior" has been replaced by "Mage", so write the updated data to the file:
with open("some_file.txt","w") as f:
for line in newline:
f.writelines(line)
This is what the output will be in both cases:
Dan Dan
Warrior ------> Mage
500 500
1 1
0 0
Try:
if (textBox1.Text == "" || textBox2.Text == "")
{
// do something..
}
Instead of:
if (textBox1.Text == string.Empty || textBox2.Text == string.Empty)
{
// do something..
}
Because string.Empty is different than - "".
Updated for iOS 8.0
Since iOS 8.0, you will need to use UIAlertController as the following:
-(void)alertMessage:(NSString*)message
{
UIAlertController* alert = [UIAlertController
alertControllerWithTitle:@"Alert"
message:message
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* defaultAction = [UIAlertAction
actionWithTitle:@"OK" style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action) {}];
[alert addAction:defaultAction];
[self presentViewController:alert animated:YES completion:nil];
}
Where self in my example is a UIViewController, which implements "presentViewController" method for a popup.
David
In Android Studio, go to app -> src -> main -> java -> com.example.username.projectname
Right click on com.example.username.projectname -> Activity -> ActivityType
Fill in the details of the New Android Activity and click Finish.
Viola! new activity added to the existing project.
From this question.
You can try to change your compiler level back to 1.7 in the IDE you're using.
If you're on Android Studio, you can add this to your build.gradle
android {
compileSdkVersion 19
buildToolsVersion "19.0.0"
defaultConfig {
minSdkVersion 7
targetSdkVersion 19
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_7
targetCompatibility JavaVersion.VERSION_1_7
}
}
If this doesn't help, try checking other's answer in the link mentioned above and let us know what helped you.
You can use the function system
.
system("color *background**foreground*");
For background and foreground, type in a number from 0 - 9 or a letter from A - F.
For example:
system("color A1");
std::cout<<"hi"<<std::endl;
That would display the letters "hi" with a green background and blue text.
To see all the color choices, just type in:
system("color %");
to see what number or letter represents what color.
Mine was putting the schema on the table Alias by mistake:
SELECT * FROM schema.CustomerOrders co
WHERE schema.co.ID = 1 -- oops!
Actually, jQuery has a built in trim function:
var emailAdd = jQuery.trim($(this).text());
See here for details.
I had this problem, but I didn't want to use annotation in my entities, so I solved by creating a constructor for my class, this constructor must not have a reference back to the entities who references this entity. Let's say this scenario.
public class A{
private int id;
private String code;
private String name;
private List<B> bs;
}
public class B{
private int id;
private String code;
private String name;
private A a;
}
If you try to send to the view the class B
or A
with @ResponseBody
it may cause an infinite loop. You can write a constructor in your class and create a query with your entityManager
like this.
"select new A(id, code, name) from A"
This is the class with the constructor.
public class A{
private int id;
private String code;
private String name;
private List<B> bs;
public A(){
}
public A(int id, String code, String name){
this.id = id;
this.code = code;
this.name = name;
}
}
However, there are some constrictions about this solution, as you can see, in the constructor I did not make a reference to List bs this is because Hibernate does not allow it, at least in version 3.6.10.Final, so when I need to show both entities in a view I do the following.
public A getAById(int id); //THE A id
public List<B> getBsByAId(int idA); //the A id.
The other problem with this solution, is that if you add or remove a property you must update your constructor and all your queries.
B business day frequency
C custom business day frequency (experimental)
D calendar day frequency
W weekly frequency
M month end frequency
SM semi-month end frequency (15th and end of month)
BM business month end frequency
CBM custom business month end frequency
MS month start frequency
SMS semi-month start frequency (1st and 15th)
BMS business month start frequency
CBMS custom business month start frequency
Q quarter end frequency
BQ business quarter endfrequency
QS quarter start frequency
BQS business quarter start frequency
A year end frequency
BA, BY business year end frequency
AS, YS year start frequency
BAS, BYS business year start frequency
BH business hour frequency
H hourly frequency
T, min minutely frequency
S secondly frequency
L, ms milliseconds
U, us microseconds
N nanoseconds
See the timeseries documentation. It includes a list of offsets (and 'anchored' offsets), and a section about resampling.
Note that there isn't a list of all the different how
options, because it can be any NumPy array function and any function that is available via groupby dispatching can be passed to how
by name.
jQuery offers $.inArray
:
Note that inArray returns the index of the element found, so 0
indicates the element is the first in the array. -1
indicates the element was not found.
var categoriesPresent = ['word', 'word', 'specialword', 'word'];_x000D_
var categoriesNotPresent = ['word', 'word', 'word'];_x000D_
_x000D_
var foundPresent = $.inArray('specialword', categoriesPresent) > -1;_x000D_
var foundNotPresent = $.inArray('specialword', categoriesNotPresent) > -1;_x000D_
_x000D_
console.log(foundPresent, foundNotPresent); // true false
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
Edit 3.5 years later
$.inArray
is effectively a wrapper for Array.prototype.indexOf
in browsers that support it (almost all of them these days), while providing a shim in those that don't. It is essentially equivalent to adding a shim to Array.prototype
, which is a more idiomatic/JSish way of doing things. MDN provides such code. These days I would take this option, rather than using the jQuery wrapper.
var categoriesPresent = ['word', 'word', 'specialword', 'word'];_x000D_
var categoriesNotPresent = ['word', 'word', 'word'];_x000D_
_x000D_
var foundPresent = categoriesPresent.indexOf('specialword') > -1;_x000D_
var foundNotPresent = categoriesNotPresent.indexOf('specialword') > -1;_x000D_
_x000D_
console.log(foundPresent, foundNotPresent); // true false
_x000D_
Edit another 3 years later
Gosh, 6.5 years?!
The best option for this in modern Javascript is Array.prototype.includes
:
var found = categories.includes('specialword');
No comparisons and no confusing -1
results. It does what we want: it returns true
or false
. For older browsers it's polyfillable using the code at MDN.
var categoriesPresent = ['word', 'word', 'specialword', 'word'];_x000D_
var categoriesNotPresent = ['word', 'word', 'word'];_x000D_
_x000D_
var foundPresent = categoriesPresent.includes('specialword');_x000D_
var foundNotPresent = categoriesNotPresent.includes('specialword');_x000D_
_x000D_
console.log(foundPresent, foundNotPresent); // true false
_x000D_
public void getClientNameDropDowndata()
{
getConnection = Connection.SetConnection(); // to connect with data base Configure manager
string ClientName = "Select ClientName from Client ";
SqlCommand ClientNameCommand = new SqlCommand(ClientName, getConnection);
ClientNameCommand.CommandType = CommandType.Text;
SqlDataReader ClientNameData;
ClientNameData = ClientNameCommand.ExecuteReader();
if (ClientNameData.HasRows)
{
DropDownList_ClientName.DataSource = ClientNameData;
DropDownList_ClientName.DataValueField = "ClientName";
DropDownList_ClientName.DataTextField="ClientName";
DropDownList_ClientName.DataBind();
}
else
{
MessageBox.Show("No is found");
CloseConnection = new Connection();
CloseConnection.closeConnection(); // close the connection
}
}
It's really simple, just download the latest toolkit from Codeplex and add the extracted AjaxControlToolkit.dll
to your toolbox in Visual Studio by right clicking the toolbox and selecting 'choose items'. You will then have the controls in your Visual STudio toolbox and using them is just a matter of dragging and dropping them onto your form, of course don't forget to add a asp:ScriptManager
to every page that uses controls from the toolkit, or optionally include it in your master page only and your content pages will inherit the script manager.
This did the trick for me coming from Brackets and being used to ctrl+/ on the numpad.
[
{ "keys": ["ctrl+keypad_divide"], "command": "toggle_comment", "args": { "block": false } },
{ "keys": ["ctrl+shift+keypad_divide"], "command": "toggle_comment", "args": { "block": true } }
]
ALTER TABLE Testing ALTER COLUMN TestDec decimal(16,1)
Just put decimal(precision, scale)
, replacing the precision and scale with your desired values.
I haven't done any testing with this with data in the table, but if you alter the precision, you would be subject to losing data if the new precision is lower.
function foo() {_x000D_
function bar() {_x000D_
return 1;_x000D_
}_x000D_
}_x000D_
bar();
_x000D_
bar
is defined inside foo
, bar
will only be accessible inside foo
.bar
you need to run it inside foo
. function foo() {_x000D_
function bar() {_x000D_
return 1;_x000D_
}_x000D_
bar();_x000D_
}
_x000D_
The size of your image is not sufficient to see in a naked eye. So please try to use atleast 50x50
import cv2 as cv
import numpy as np
black_screen = np.zeros([50,50,3])
black_screen[:, :, 2] = np.ones([50,50])*64/255.0
cv.imshow("Simple_black", black_screen)
cv.waitKey(0)
cv.displayAllWindows()
You can useflatten()
from the numpy package.
import numpy as np
a = np.array([[1, 2],
[3, 4],
[5, 6]])
a_flat = a.flatten()
print(f"original array: {a} \nflattened array = {a_flat}")
Output:
original array: [[1 2]
[3 4]
[5 6]]
flattened array = [1 2 3 4 5 6]
aList=[1,2,3]
i=0
for item in aList:
if i<2:
aList.remove(item)
i+=1
aList
[2]
The moral is when modifying a list in a loop driven by the list, takes two steps:
aList=[1,2,3]
i=0
for item in aList:
if i<2:
aList[i]="del"
i+=1
aList
['del', 'del', 3]
for i in range(2):
del aList[0]
aList
[3]
execute the below code to get the foreign key constraint name which blocks your drop. For example, I take the roles
table.
SELECT *
FROM sys.foreign_keys
WHERE referenced_object_id = object_id('roles');
SELECT name AS 'Foreign Key Constraint Name',
OBJECT_SCHEMA_NAME(parent_object_id) + '.' + OBJECT_NAME(parent_object_id)
AS 'Child Table' FROM sys.foreign_keys
WHERE OBJECT_SCHEMA_NAME(referenced_object_id) = 'dbo'
AND OBJECT_NAME(referenced_object_id) = 'dbo.roles'
you will get the FK name something as below : FK__Table1__roleId__1X1H55C1
now run the below code to remove the FK reference got from above.
ALTER TABLE dbo.users drop CONSTRAINT FK__Table1__roleId__1X1H55C1;
Done!
Here is the simplest way:
Guid guid = Guid.NewGuid();
Random random = new Random();
int i = random.Next();
You'll notice that guid
is not actually used here, mainly because there would be no point in using it. Microsoft's GUID algorithm does not use the computer's MAC address any more - GUID's are actually generated using a pseudo-random generator (based on time values), so if you want a random integer it makes more sense to use the Random
class for this.
Update: actually, using a GUID to generate an int
would probably be worse than just using Random
("worse" in the sense that this would be more likely to generate collisions). This is because not all 128 bits in a GUID are random. Ideally, you would want to exclude the non-varying bits from a hashing function, although it would be a lot easier to just generate a random number, as I think I mentioned before. :)
I believe that XDocument
makes a lot more object creation calls. I suspect that for when you're handling a lot of XML documents, XMLDocument
will be faster.
One place this happens is in managing scan data. Many scan tools output their data in XML (for obvious reasons). If you have to process a lot of these scan files, I think you'll have better performance with XMLDocument
.
See TRY...CATCH (Transact-SQL)
CREATE PROCEDURE [dbo].[PL_GEN_PROVN_NO1]
@GAD_COMP_CODE VARCHAR(2) =NULL,
@@voucher_no numeric =null output
AS
BEGIN
begin try
-- your proc code
end try
begin catch
-- what you want to do in catch
end catch
END -- proc end
This script demonstrates a few ways to show the local timezone using astimezone()
:
#!/usr/bin/env python3
import pytz
from datetime import datetime, timezone
from tzlocal import get_localzone
utc_dt = datetime.now(timezone.utc)
PST = pytz.timezone('US/Pacific')
EST = pytz.timezone('US/Eastern')
JST = pytz.timezone('Asia/Tokyo')
NZST = pytz.timezone('Pacific/Auckland')
print("Pacific time {}".format(utc_dt.astimezone(PST).isoformat()))
print("Eastern time {}".format(utc_dt.astimezone(EST).isoformat()))
print("UTC time {}".format(utc_dt.isoformat()))
print("Japan time {}".format(utc_dt.astimezone(JST).isoformat()))
# Use astimezone() without an argument
print("Local time {}".format(utc_dt.astimezone().isoformat()))
# Use tzlocal get_localzone
print("Local time {}".format(utc_dt.astimezone(get_localzone()).isoformat()))
# Explicitly create a pytz timezone object
# Substitute a pytz.timezone object for your timezone
print("Local time {}".format(utc_dt.astimezone(NZST).isoformat()))
It outputs the following:
$ ./timezones.py
Pacific time 2019-02-22T17:54:14.957299-08:00
Eastern time 2019-02-22T20:54:14.957299-05:00
UTC time 2019-02-23T01:54:14.957299+00:00
Japan time 2019-02-23T10:54:14.957299+09:00
Local time 2019-02-23T14:54:14.957299+13:00
Local time 2019-02-23T14:54:14.957299+13:00
Local time 2019-02-23T14:54:14.957299+13:00
As of python 3.6 calling astimezone()
without a timezone object defaults to the local zone (docs). This means you don't need to import tzlocal
and can simply do the following:
#!/usr/bin/env python3
from datetime import datetime, timezone
utc_dt = datetime.now(timezone.utc)
print("Local time {}".format(utc_dt.astimezone().isoformat()))
I hope to provide more background knowledge here.
First, constructor signature of the of method threading::Thread:
class threading.Thread(group=None, target=None, name=None, args=(), kwargs={}, *, daemon=None)
args is the argument tuple for the target invocation. Defaults to ().
Second, A quirk in Python about tuple
:
Empty tuples are constructed by an empty pair of parentheses; a tuple with one item is constructed by following a value with a comma (it is not sufficient to enclose a single value in parentheses).
On the other hand, a string is a sequence of characters, like 'abc'[1] == 'b'
. So if send a string to args
, even in parentheses (still a sting), each character will be treated as a single parameter.
However, Python is so integrated and is not like JavaScript where extra arguments can be tolerated. Instead, it throws an TypeError
to complain.
Check your short_open_tag setting (use <?php phpinfo() ?>
to see its current setting).
I recommend using Kingfisher library to download images asynchronously. The best part about using Kingfisher is, it caches all the downloaded images by default with the image url as an id. Next time when you request to download image with that particular URl, it will load it from cache.
Usage:
newsImage.kf.setImage(with: imageUrl!, placeholder: nil, options: nil, progressBlock: nil, completionHandler: { (image, error, cacheType, imageUrl) in
if error == nil{
self.activityIndicator.stopAnimating()
}else if error != nil{
self.activityIndicator.stopAnimating()
}
})
I think MAVEN_OPTS
would be most appropriate for you. See here: http://maven.apache.org/configure.html
In Unix:
Add the
MAVEN_OPTS
environment variable to specify JVM properties, e.g.export MAVEN_OPTS="-Xms256m -Xmx512m"
. This environment variable can be used to supply extra options to Maven.
In Win, you need to set environment variable via the dialogue box
Add ... environment variable by opening up the system properties (
WinKey + Pause
),... In the same dialog, add theMAVEN_OPTS
environment variable in the user variables to specify JVM properties, e.g. the value-Xms256m -Xmx512m
. This environment variable can be used to supply extra options to Maven.
Builder Pattern and Factory pattern, both seem pretty similar to naked eyes because they both create objects for you.
This real-life example will make the difference between the two more clear.
Suppose, you went to a fast food restaurant and you ordered Food.
Pizza
Capsicum, Tomato, BBQ chicken, NO PINEAPPLE
So different kinds of foods are made by Factory pattern but the different variants(flavors) of a particular food are made by Builder pattern.
Different kinds of foods
Pizza, Burger, Pasta
Variants of Pizza
Only Cheese, Cheese+Tomato+Capsicum, Cheese+Tomato etc.
You can see the sample code implementation of both patterns here
Builder Pattern
Factory Pattern
I know this question is pretty old now, but I thought you might have an easier time with ElementTree
from xml.etree import ElementTree as ET
import datetime
f = ET.XML(data)
for element in f:
if element.tag == "currentTime":
# Handle time data was pulled
currentTime = datetime.datetime.strptime(element.text, "%Y-%m-%d %H:%M:%S")
if element.tag == "cachedUntil":
# Handle time until next allowed update
cachedUntil = datetime.datetime.strptime(element.text, "%Y-%m-%d %H:%M:%S")
if element.tag == "result":
# Process list of skills
pass
I know that's not super specific, but I just discovered it, and so far it's a lot easier to get my head around than the minidom (since so many nodes are essentially white space).
For instance, you have the tag name and the actual text together, just as you'd probably expect:
>>> element[0]
<Element currentTime at 40984d0>
>>> element[0].tag
'currentTime'
>>> element[0].text
'2010-04-12 02:45:45'e
The prestListView.getItemAtPosition(position); returns the UI widget: Text, Icon, ...
Try this instead:
Object o = prestationAdapterEco.getItemAtPosition(position);
or
Object o = arg0.getItemAtPosition(position);
Get the object from the adapter. Not from the list-view.
2. Object o is a prestationEco object. Not a String.
Erm, after understanding your question: are you sure that the signature-method only creates a SHA1 and encrypts it? GPG et al offer to compress/clear sign the data. Maybe this java-signature-alg also creates a detachable/attachable signature.
Go to res
package and open color.xml
.
Set color primary to #00000000
.
to use parameters in aliases, i use this method:
alias myalias='function __myalias() { echo "Hello $*"; unset -f __myalias; }; __myalias'
its a self-destructive function wrapped in an alias, so it pretty much is the best of both worlds, and doesnt take up an extra line(s) in your definitions... which i hate, oh yeah and if you need that return value, you'll have to store it before calling unset, and then return the value using the "return" keyword in that self destructive function there:
alias myalias='function __myalias() { echo "Hello $*"; myresult=$?; unset -f __myalias; return $myresult; }; __myalias'
so..
you could, if you need to have that variable in there
alias mongodb='function __mongodb() { ./path/to/mongodb/$1; unset -f __mongodb; }; __mongodb'
of course...
alias mongodb='./path/to/mongodb/'
would actually do the same thing without the need for parameters, but like i said, if you wanted or needed them for some reason (for example, you needed $2 instead of $1), you would need to use a wrapper like that. If it is bigger than one line you might consider just writing a function outright since it would become more of an eyesore as it grew larger. Functions are great since you get all the perks that functions give (see completion, traps, bind, etc for the goodies that functions can provide, in the bash manpage).
I hope that helps you out :)
Change
document.getElementById('personlist').getElementsByTagName('option')[11].selected = 'selected'
to
document.getElementById('personlist').value=Person_ID;
A cleaner approach would be to create a Person
object that contains contactName
, contactPhone
, etc. Then, use an ArrayList
rather then an array to add the new objects. Create a loop that accepts all the fields for each `Person:
while (!done) {
Person person = new Person();
String name = input.nextLine();
person.setContactName(name);
...
myPersonList.add(person);
}
Using the list will remove the need for array bounds checking.
I was able to figure it out. In case someone wants to know below the code that worked for me:
ASCIIEncoding ascii = new ASCIIEncoding();
byte[] byteArray = Encoding.UTF8.GetBytes(sOriginal);
byte[] asciiArray = Encoding.Convert(Encoding.UTF8, Encoding.ASCII, byteArray);
string finalString = ascii.GetString(asciiArray);
Let me know if there is a simpler way o doing it.
I think this String.Equals is what you need.
Dim aaa = "12/31"
Dim a = String.Equals(aaa, "06/30")
a will return false.
have you looked at layoutIfNeeded?
The documentation snippet is below. Does the animation work if you call this method explicitly during the animation?
layoutIfNeeded Lays out the subviews if needed.
- (void)layoutIfNeeded
Discussion Use this method to force the layout of subviews before drawing.
Availability Available in iPhone OS 2.0 and later.
library(RCurl)
library(XML)
# Download page using RCurl
# You may need to set proxy details, etc., in the call to getURL
theurl <- "http://en.wikipedia.org/wiki/Brazil_national_football_team"
webpage <- getURL(theurl)
# Process escape characters
webpage <- readLines(tc <- textConnection(webpage)); close(tc)
# Parse the html tree, ignoring errors on the page
pagetree <- htmlTreeParse(webpage, error=function(...){})
# Navigate your way through the tree. It may be possible to do this more efficiently using getNodeSet
body <- pagetree$children$html$children$body
divbodyContent <- body$children$div$children[[1]]$children$div$children[[4]]
tables <- divbodyContent$children[names(divbodyContent)=="table"]
#In this case, the required table is the only one with class "wikitable sortable"
tableclasses <- sapply(tables, function(x) x$attributes["class"])
thetable <- tables[which(tableclasses=="wikitable sortable")]$table
#Get columns headers
headers <- thetable$children[[1]]$children
columnnames <- unname(sapply(headers, function(x) x$children$text$value))
# Get rows from table
content <- c()
for(i in 2:length(thetable$children))
{
tablerow <- thetable$children[[i]]$children
opponent <- tablerow[[1]]$children[[2]]$children$text$value
others <- unname(sapply(tablerow[-1], function(x) x$children$text$value))
content <- rbind(content, c(opponent, others))
}
# Convert to data frame
colnames(content) <- columnnames
as.data.frame(content)
Edited to add:
Sample output
Opponent Played Won Drawn Lost Goals for Goals against % Won
1 Argentina 94 36 24 34 148 150 38.3%
2 Paraguay 72 44 17 11 160 61 61.1%
3 Uruguay 72 33 19 20 127 93 45.8%
...
Try this
getExternalFilesDir(Environment.getDataDirectory().getAbsolutePath()).getAbsolutePath()
any hashing method that evenly distributes the hash value over the possible range is a good implementation. See effective java ( http://books.google.com.au/books?id=ZZOiqZQIbRMC&dq=effective+java&pg=PP1&ots=UZMZ2siN25&sig=kR0n73DHJOn-D77qGj0wOxAxiZw&hl=en&sa=X&oi=book_result&resnum=1&ct=result ) , there is a good tip in there for hashcode implementation (item 9 i think...).
You can use sshpass for it. Below are the steps
sudo apt-get install sshpass
sshpass -p '#Password_For_remote_machine' scp /home/ubuntu/latest_build/abc.war #user@#RemoteIP:/var/lib/tomcat7/webapps
if all you're trying to do is get the value of a single entry in a map, there's no need to loop over any collection at all. simplifying gautum's response slightly, you can get the value of a named map entry as follows:
<c:out value="${map['key']}"/>
where 'map' is the collection and 'key' is the string key for which you're trying to extract the value.
Got same error in this line
Object temp = range.Cells[i][0].Value;
Solved with non-zero based index
Object temp = range.Cells[i][1].Value;
How is it possible that the guys who created this library thought it was a good idea to use non-zero based indexing?
You can either use the answer from the duplicate link pointed by nvm.
Or you can resolve conflicts by using their changes (but some of your changes might be kept if they don't conflict with remote version):
git pull -s recursive -X theirs
Borrowing from Zyphrax's answer ...
USE DatabaseName
DECLARE @ReseedBit BIT =
COALESCE((SELECT SUM(CONVERT(BIGINT, ic.last_value))
FROM sys.identity_columns ic
INNER JOIN sys.tables t ON ic.object_id = t.object_id), 0)
DECLARE @Reseed INT =
CASE
WHEN @ReseedBit = 0 THEN 1
WHEN @ReseedBit = 1 THEN 0
END
DBCC CHECKIDENT ('dbo.table_name', RESEED, @Reseed);
Caveats: This is intended for use in reference data population situations where a DB is being initialized with enum type definition tables, where the ID values in those tables must always start at 1. The first time the DB is being created (e.g. during SSDT-DB publishing) @Reseed must be 0, but when resetting the data i.e. removing the data and re-inserting it, then @Reseed must be 1. So this code is intended for use in a stored procedure for resetting the DB data, which can be called manually but is also called from the post-deployment script in the SSDT-DB project. In that way the reference data inserts are only defined in one place but aren't restricted to be used only in post-deployment during publishing, they are also available for subsequent use (to support dev and automated test etc.) by calling the stored procedure to reset the DB back to a known good state.
I know this is very specific, but I think my answer could be helpful for certain users.
If you have node
and npm
installed on your machine, you can use js-yaml
.
First install :
npm i -g js-yaml
# or locally
npm i js-yaml
then in your bash script
#!/bin/bash
js-yaml your-yaml-file.yml
Also if you are using jq
you can do something like that
#!/bin/bash
json="$(js-yaml your-yaml-file.yml)"
aproperty="$(jq '.apropery' <<< "$json")"
echo "$aproperty"
Because js-yaml
converts a yaml file to a json string literal. You can then use the string with any json parser in your unix system.
In general, i agree with above answers that recommend to add maven dependency, but i prefer following solution.
Add a dependency with API classes for full JavaEE profile:
<properties>
<javaee-api.version>7.0</javaee-api.version>
<hibernate-entitymanager.version>5.1.3.Final</hibernate-entitymanager.version>
</properties>
<depencies>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>${javaee-api.version}</version>
<scope>provided</scope>
</dependency>
</dependencies>
Also add dependency with particular JPA provider like antonycc suggested:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate-entitymanager.version}</version>
</dependency>
Note <scope>provided</scope>
in API dependency section: this means that corresponding jar will not be exported into artifact's lib/
, but will be provided by application server. Make sure your application server implements specified version of JavaEE API.
Just check the dictionary:
d = {'hello':'world'}
if d:
print 'not empty'
else:
print 'empty'
d = {}
if d:
print 'not empty'
else:
print 'empty'
Right click on pom.xml, Run As, you should see the list of m2 options if you have Maven installed, you can select Maven Clean from there
Sometimes You just open too much applications in Windows and make the gradle have no enough memory to start the daemon process.So when you come across with this situation,you can just close some applications such as Chrome and so on. Then restart your android studio.
Just in case there's not enough answers here, here's mine :)
public static string Truncate(this string str,
int totalLength,
string truncationIndicator = "")
{
if (string.IsNullOrEmpty(str) || str.Length < totalLength)
return str;
return str.Substring(0, totalLength - truncationIndicator.Length)
+ truncationIndicator;
}
to use:
"I use it like this".Truncate(5,"~")
As far as I know, shouldOverrideUrlLoading is not called for images but rather for hyperlinks... I think the appropriate method is
@Override
public void onLoadResource(WebView view, String url)
This method is called for every resource (image, styleesheet, script) that's loaded by the webview, but since it's a void, I haven't found a way to change that url and replace it so that it loads a local resource ...
Set positioning to absolute. That will solve the problem immediately, but might cause some problems in layout later. You can always figure out a way around them ;)
Example:
position:absolute;
You are missing router exports module and that is the reason why this error is present.
use module.exports = router;
and that would work
Kevin Pope's comment under the accepted answer was what I needed.
The problem, in my case, was that I had triggers defined on my table that would insert update/insert transactions into an audit table, but the audit table had a data type mismatch where a column with VARCHAR(MAX)
in the original table was stored as VARCHAR(1)
in the audit table, so my triggers were failing when I would insert anything greater than VARCHAR(1)
in the original table column and I would get this error message.
You need to use view's layer to set border property. e.g:
#import <QuartzCore/QuartzCore.h>
...
view.layer.borderColor = [UIColor redColor].CGColor;
view.layer.borderWidth = 3.0f;
You also need to link with QuartzCore.framework to access this functionality.
If you're using Windows Terminal then the killing process might be little less tedious.
I've been using windows terminal and kill PID
works fine for me to kill processes on the port as the new Windows Terminal supports certain bash commands. For example: kill 13300
So, the complete process will look like this-
netstat -ano | findstr :PORT
kill PID
For Example:
PS C:\Users\username> netstat -ano | findstr :4445
TCP 0.0.0.0:4445 0.0.0.0:0 LISTENING 7368
TCP [::]:4445 [::]:0 LISTENING 7368
PS C:\Users\username> kill 7368
PS C:\Users\username> netstat -ano | findstr :4445
PS C:\Users\username>
See when I typed the first command to list processes on the port it returned empty. That means all processes are killed now.
Update: kill
is an alias for Stop-Process. Thanks, @FSCKur for letting us know.
To remove everything before a certain character, use a regular expression:
re.sub(r'^[^a]*', '')
to remove everything up to the first 'a'. [^a]
can be replaced with any character class you like, such as word characters.
If you have multiple aws profiles in ~/.aws/credentials
like...
[Profile 1]
aws_access_key_id = *******************
aws_secret_access_key = ******************************************
[Profile 2]
aws_access_key_id = *******************
aws_secret_access_key = ******************************************
Follow two steps:
Make one you want to use as a default using export AWS_DEFAULT_PROFILE=Profile 1
command in terminal.
Make sure to run above command in the same terminal from where you use boto3 or you open an editor.[Understand the following scenario]
Scenario:
t1
and t2
.t1
and you open JupyterLab or any other from t2
, you will get NoCredentialsError: Unable to locate credentials error.Solution:
t1
and then open JupyterLab or any other from the same terminal t1
.Another option is to add style to div
<div style="position: absolute; height:somePercentage%; overflow:auto(or other overflow value)">
//to be scrolled
</div>
And it means that an element is positioned relative to the nearest positioned ancestor.
I think it depends on how you installed python. Note that you can have multiple installs of python, I do on my machine. However, if you install via an msi of a version of python 2.2 or above, I believe it creates a registry key like so:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\Python.exe
which gives this value on my machine:
C:\Python25\Python.exe
You just read the registry key to get the location.
However, you can install python via an xcopy like model that you can have in an arbitrary place, and you just have to know where it is installed.
I had the same problem. I am using jquery-validation as an npm module and the fix for me was to require the module at the start of my js file:
require('jquery-validation');
You are passing wrong mode to you view. Your view is looking for @model IEnumerable<Standings.Models.Teams>
and you are passing var model = tm.Name.ToList();
name list. You have to pass list of Teams.
You have to pass following model
var model = new List<Teams>();
model.Add(new Teams { Name = new List<string>(){"Sky","ABC"}});
model.Add(new Teams { Name = new List<string>(){"John","XYZ"} });
return View(model);
Nice answers. You could also set Jobs (i.e., commands) with "Crontab" for more flexibility (which provides different options to run scripts, loggin the outputs, etc.), although it requires more time to be understood and set properly:
Using '@reboot' you can Run a command once, at startup.
Wrapping up:
run $ sudo crontab -e -u root
And add a line at the end of the file with your command as follows:
@reboot sudo searchd
Can also use this method
if substring in string:
print(string + '\n Yes located at:'.format(string.find(substring)))
if (UIDevice.current.identifierForVendor?.uuidString) != nil
{
self.lblDeviceIdValue.text = UIDevice.current.identifierForVendor?.uuidString
}
You should be able to match it with: /<primaryAddress>(.+?)<\/primaryAddress>/
The content between the tags will be in the matched group.
With the help of glide library and RoundedBitmapDrawableFactory class it's easy to achieve. You may need to create circular placeholder image.
Glide.with(context)
.load(imgUrl)
.asBitmap()
.placeholder(R.drawable.placeholder)
.error(R.drawable.placeholder)
.into(new BitmapImageViewTarget(imgProfilePicture) {
@Override
protected void setResource(Bitmap resource) {
RoundedBitmapDrawable drawable = RoundedBitmapDrawableFactory.create(context.getResources(),
Bitmap.createScaledBitmap(resource, 50, 50, false));
drawable.setCornerRadius(10); //drawable.setCircular(true);
imgProfilePicture.setImageDrawable(drawable);
}
});
The problem, in my case, was that some install at some point defined an environment variable http_proxy on my machine when I had no proxy.
Removing the http_proxy environment variable fixed the problem.
{ }
-->
defines scope, so if(a==1) { int b = 10; }
says, you are defining int b, for {}- this scope. For
if(a==1)
int b =10;
there is no scope. And you will not be able to use b
anywhere.
A generic solution with a timeout:
import time
def onerror_retry(exception, callback, timeout=2, timedelta=.1):
end_time = time.time() + timeout
while True:
try:
yield callback()
break
except exception:
if time.time() > end_time:
raise
elif timedelta > 0:
time.sleep(timedelta)
Usage:
for retry in onerror_retry(SomeSpecificException, do_stuff):
retry()
A bit late but I tried this and it worked to make the Recaptcha responsive on screens smaller than 460px width. You can't use css selector to select elements inside the iframe. So, better use the outermost parent element which is the class g-recaptcha to basically zoom-out i.e transform the size of the entire container. Here's my code which worked:
@media(max-width:459.99px) {
.modal .g-recaptcha {
transform:scale(0.75);
-webkit-transform:scale(0.75); }
}
}
Update: I noticed that my answer was just a poor duplicate of a well explained question on https://unix.stackexchange.com/... by BryKKan
Here is an extract from it:
openssl pkcs12 -in <filename.pfx> -nocerts -nodes | sed -ne '/-BEGIN PRIVATE KEY-/,/-END PRIVATE KEY-/p' > <clientcert.key>
openssl pkcs12 -in <filename.pfx> -clcerts -nokeys | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > <clientcert.cer>
openssl pkcs12 -in <filename.pfx> -cacerts -nokeys -chain | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > <cacerts.cer>
I know that's an old question with good answers, but I believe I can add my 2 cents.
The simplest and most flexible way which works for me is just using an almost "Plain and Old Java Object" class2D to create each "row" of your array.
The below example has some explanations and is executable (you can copy and paste it, but remember to check the package name):
package my2darraylist;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JPanel;
public class My2DArrayList
{
public static void main(String[] args)
{
// This is your "2D" ArrayList
//
List<Box> boxes = new ArrayList<>();
// Add your stuff
//
Box stuff = new Box();
stuff.setAString( "This is my stuff");
stuff.addString("My Stuff 01");
stuff.addInteger( 1 );
boxes.add( stuff );
// Add other stuff
//
Box otherStuff = new Box();
otherStuff.setAString( "This is my other stuff");
otherStuff.addString("My Other Stuff 01");
otherStuff.addInteger( 1 );
otherStuff.addString("My Other Stuff 02");
otherStuff.addInteger( 2 );
boxes.add( otherStuff );
// List the whole thing
for ( Box box : boxes)
{
System.out.println( box.getAString() );
System.out.println( box.getMyStrings().size() );
System.out.println( box.getMyIntegers().size() );
}
}
}
class Box
{
// Each attribute is a "Column" in you array
//
private String aString;
private List<String> myStrings = new ArrayList<>() ;
private List<Integer> myIntegers = new ArrayList<>();
// Use your imagination...
//
private JPanel jpanel;
public void addString( String s )
{
myStrings.add( s );
}
public void addInteger( int i )
{
myIntegers.add( i );
}
// Getters & Setters
public String getAString()
{
return aString;
}
public void setAString(String aString)
{
this.aString = aString;
}
public List<String> getMyStrings()
{
return myStrings;
}
public void setMyStrings(List<String> myStrings)
{
this.myStrings = myStrings;
}
public List<Integer> getMyIntegers()
{
return myIntegers;
}
public void setMyIntegers(List<Integer> myIntegers)
{
this.myIntegers = myIntegers;
}
public JPanel getJpanel()
{
return jpanel;
}
public void setJpanel(JPanel jpanel)
{
this.jpanel = jpanel;
}
}
UPDATE - To answer the question from @Mohammed Akhtar Zuberi, I've created the simplified version of the program, to make it easier to show the results.
import java.util.ArrayList;
public class My2DArrayListSimplified
{
public static void main(String[] args)
{
ArrayList<Row> rows = new ArrayList<>();
Row row;
// Insert the columns for each row
// First Name, Last Name, Age
row = new Row("John", "Doe", 30);
rows.add(row);
row = new Row("Jane", "Doe", 29);
rows.add(row);
row = new Row("Mary", "Doe", 1);
rows.add(row);
// Show the Array
//
System.out.println("First\t Last\tAge");
System.out.println("----------------------");
for (Row printRow : rows)
{
System.out.println(
printRow.getFirstName() + "\t " +
printRow.getLastName() + "\t" +
printRow.getAge());
}
}
}
class Row
{
// REMEMBER: each attribute is a column
//
private final String firstName;
private final String lastName;
private final int age;
public Row(String firstName, String lastName, int age)
{
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
public String getFirstName()
{
return firstName;
}
public String getLastName()
{
return lastName;
}
public int getAge()
{
return age;
}
}
The code above produces the following result (I ran it on NetBeans):
run:
First Last Age
----------------------
John Doe 30
Jane Doe 29
Mary Doe 1
BUILD SUCCESSFUL (total time: 0 seconds)
inline void format(string& a_string, const char* fmt, ...)
{
va_list vl;
va_start(vl, fmt);
int size = _vscprintf( fmt, vl );
a_string.resize( ++size );
vsnprintf_s((char*)a_string.data(), size, _TRUNCATE, fmt, vl);
va_end(vl);
}
Just import tensortflow and use keras, it's that easy.
import tensorflow as tf
# your code here
with tf.device('/gpu:0'):
model.fit(X, y, epochs=20, batch_size=128, callbacks=callbacks_list)
I have been researching this for a while, tested and wrote apps.
If you have no option in Settings ? Phone ? Use proximity sensor
, then the only choice, seem to be to disable or modify its settings in rooted devices.
Also consider, that if you plug the headset, the screen will remain on :D
If you have access to your apache install and trust third-party code, you can use the apache upload progress module (if you use apache; there's also a nginx upload progress module).
Otherwise, you'd have to write a script that you can hit out of band to request the status of the file (checking the filesize of the tmp file for instance).
There's some work going on in firefox 3 I believe to add upload progress support to the browser, but that's not going to get into all the browsers and be widely adopted for a while (more's the pity).
a = ["item 1", "item 2", "item 3", "item 4"]
h = Hash[*a] # => { "item 1" => "item 2", "item 3" => "item 4" }
That's it. The *
is called the splat operator.
One caveat per @Mike Lewis (in the comments): "Be very careful with this. Ruby expands splats on the stack. If you do this with a large dataset, expect to blow out your stack."
So, for most general use cases this method is great, but use a different method if you want to do the conversion on lots of data. For example, @Lukasz Niemier (also in the comments) offers this method for large data sets:
h = Hash[a.each_slice(2).to_a]
You could also add an offset if you want to use negative indexes:
uint8_t l_matrix[10][20];
uint8_t (*matrix_ptr)[20] = l_matrix+5;
matrix_ptr[-4][1]=7;
If your compiler gives an error or warning you could use:
uint8_t (*matrix_ptr)[20] = (uint8_t (*)[20]) l_matrix;
public static string RandomString(int length)
{
const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
var random = new Random();
return new string(Enumerable.Repeat(chars, length).Select(s => s[random.Next(s.Length)]).ToArray());
}
Follow the link https://datatables.net/blog/2014-12-18
A very easy way to integrate ordering by date.
<script type="text/javascript" charset="utf8" src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.8.4/moment.min.js"></script>
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/plug-ins/1.10.19/sorting/datetime-moment.js"></script>
Put this code in before initializing the datatable:
$(document).ready(function () {
// ......
$.fn.dataTable.moment('DD-MMM-YY HH:mm:ss');
$.fn.dataTable.moment('DD.MM.YYYY HH:mm:ss');
// And any format you need
}
I was stuck with ast.literal_eval()
. I was trying it in IntelliJ IDEA debugger, and it kept returning None
on debugger output.
But later when I assigned its output to a variable and printed it in code. It worked fine. Sharing code example:
import ast
sample_string = '[{"id":"XYZ_GTTC_TYR", "name":"Suction"}]'
output_value = ast.literal_eval(sample_string)
print(output_value)
Its python version 3.6.
There is no way to know unless the particular company reveals the info. The best you can do is find a few companies that are sharing and then extrapolate based on app ranking (which is available publicly). The best you'll get is a ball park estimate.
I faced this problem too. Re-ran the Visual Studio 2017 Installer, go to 'Individual Components' and select Windows 8.1 SDK
. Go back to to the project > Right click and Re-target to match the SDK required as shown below:
let str = "Hello World"
console.log(str.substring(1, 3)) // el -> Excludes the last index
console.log(str.substr(1, 3)) // ell -> Includes the last index
I had this problem on Visual Studio 2015 edition. When I used cmake to generate a project this error appeared.
error MSB4019: The imported project "D:\Microsoft.Cpp.Default.props" was not found
I fixed it by adding a String
VCTargetsPath
with value
$(MSBuildExtensionsPath32)\Microsoft.Cpp\v4.0\V140
in the registry path
HKLM\SOFTWARE\Microsoft\MSBuild\ToolsVersions\14.0
Received SQLSTATE 01000 in the following error message below:
SQL Agent - Jobs Failed: The SQL Agent Job "LiteSpeed Backup Full" has failed with the message "The job failed. The Job was invoked by User X. The last step to run was step 1 (Step1). NOTE: Failed to notify via email. - Executed as user: X. LiteSpeed(R) for SQL Server Version 6.5.0.1460 Copyright 2011 Quest Software, Inc. [SQLSTATE 01000] (Message 1) LiteSpeed for SQL Server could not open backup file: (N:\BACKUP2\filename.BAK). The previous system message is the reason for the failure. [SQLSTATE 42000] (Error 60405). The step failed."
In my case this was related to permission on drive N following an SQL Server failover on an Active/Passive SQL cluster.
All SQL resources where failed over to the seconary resouce and back to the preferred node following maintenance. When the Quest LiteSpeed job then executed on the preferred node it was clear the previous permissions for SQL server user X had been lost on drive N and SQLSTATE 10100 was reported.
Simply added the permissions again to the backup destination drive and the issue was resolved.
Hope that helps someone.
Windows 2008 Enterprise
SQL Server 2008 Active/Passive cluster.
I know this question has already been answered, but another option is simply to open the destination and source folders in Finder and then drag and drop them into the terminal. The paths will automatically be copied and properly formatted (thus negating the need to actually figure out proper file names/extensions).
I have to do over-network copies between Mac and Windows machines, sometimes fairly deep down in filetrees, and have found this the most effective way to do so.
So, as an example:
cp -r [drag and drop source folder from finder] [drag and drop destination folder from finder]
Please read the Threading Model in UI applications (old VB link is here) in order to understand basic concepts. The link navigates to page that describes the WPF threading model. However, Windows Forms utilizes the same idea.
Read answers on question How to update the GUI from another thread in C#?. For C# 5.0 and .NET 4.5 the recommended solution is here.
Look into using the ToString()
method with a specified format.
You can query the data dictionary/catalog views to find out when an object was created as well as the time of last DDL involving the object (example: alter table)
select *
from all_objects
where owner = '<name of schema owner>'
and object_name = '<name of table>'
The column "CREATED" tells you when the object was created. The column "LAST_DDL_TIME" tells you when the last DDL was performed against the object.
As for when a particular row was inserted/updated, you can use audit columns like an "insert_timestamp" column or use a trigger and populate an audit table
Just click on "Build" on the top menu and then click on "Publish ".... Then a pop up will open and there u can define the folder which u want to save the .exe file and by clicking "Next" will allow u to set up the advanced settings... DONE!
Chain both class selectors (without a space in between):
.foo.bar {
/* Styles for element(s) with foo AND bar classes */
}
If you still have to deal with ancient browsers like IE6, be aware that it doesn't read chained class selectors correctly: it'll only read the last class selector (.bar
in this case) instead, regardless of what other classes you list.
To illustrate how other browsers and IE6 interpret this, consider this CSS:
* {
color: black;
}
.foo.bar {
color: red;
}
Output on supported browsers is:
<div class="foo">Hello Foo</div> <!-- Not selected, black text [1] -->
<div class="foo bar">Hello World</div> <!-- Selected, red text [2] -->
<div class="bar">Hello Bar</div> <!-- Not selected, black text [3] -->
Output on IE6 is:
<div class="foo">Hello Foo</div> <!-- Not selected, black text [1] -->
<div class="foo bar">Hello World</div> <!-- Selected, red text [2] -->
<div class="bar">Hello Bar</div> <!-- Selected, red text [2] -->
Footnotes:
foo
.foo
and bar
.bar
.
bar
.bar
, regardless of any other classes listed.How about this?
Assuming you have System.Windows.Forms referenced.
var cbtnToggler = new CheckBox();
cbtnToggler.Appearance = Appearance.Button;
cbtnToggler.TextAlign = ContentAlignment.MiddleCenter;
cbtnToggler.MinimumSize = new Size(75, 25); //To prevent shrinkage!
Hope this helps ;)
Separating HTML from PHP is the best method. It's less confusing and easy to debug.
<?php
while($var)
{
?>
<div>
<h3><a href="User<?php echo $i;?>"><?php echo $i;?></a></h3>
<div>Lorem ipsum dolor sit amet.</div>
</div>
<?php
$i++;
}
?>
Absolute easiest way (with your current code) is to add a require_once("path/to/file")
statement to your php code.
<?php
require_once("../myCSSfile.css");
echo "<table>";
...
Also, as an aside: the opening <?php
tag does not have a >
on the end, and the closing ?>
php tag does not start with <
. Weird, but true.
When using GetAsync with the HttpClient you can add the authorization headers like so:
httpClient.DefaultRequestHeaders.Authorization
= new AuthenticationHeaderValue("Bearer", "Your Oauth token");
This does add the authorization header for the lifetime of the HttpClient so is useful if you are hitting one site where the authorization header doesn't change.
Here is an detailed SO answer
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy MM dd");
String text = date.toString(formatter);
LocalDate date = LocalDate.parse(text, formatter);
I believe this might help, you may need to use some sort of localdate variation instead of instant
Prefix the call with Module2 (ex. Module2.IDLE
). I'm assuming since you asked this that you have IDLE defined multiple times in the project, otherwise this shouldn't be necessary.
One place where it's useful is for UI activities, like setting a spinner before a lengthy operation:
- (void) handleDoSomethingButton{
[mySpinner startAnimating];
(do something lengthy)
[mySpinner stopAnimating];
}
will not work, because you are blocking the main thread during your lengthy thing and not letting UIKit actually start the spinner.
- (void) handleDoSomethingButton{
[mySpinner startAnimating];
dispatch_async (dispatch_get_main_queue(), ^{
(do something lengthy)
[mySpinner stopAnimating];
});
}
will return control to the run loop, which will schedule UI updating, starting the spinner, then will get the next thing off the dispatch queue, which is your actual processing. When your processing is done, the animation stop is called, and you return to the run loop, where the UI then gets updated with the stop.
I used this method:
$(document).mousemove(function(e) {
window.x = e.pageX;
window.y = e.pageY;
});
function show_popup(str) {
$("#popup_content").html(str);
$("#popup").fadeIn("fast");
$("#popup").css("top", y);
$("#popup").css("left", x);
}
In this way I'll always have the distance from the top saved in y and the distance from the left saved in x.
if r, g, b = 3 integer values from 0 to 255 for each color
then
rgb = 65536 * r + 256 * g + b;
the single rgb value is the composite value of r,g,b combined for a total of 16777216 possible shades.
localStorage.clear()
That'll clear the stored data. Then refresh and things should start to work.
When you call figure
, simply number the plot.
x = arange(5)
y = np.exp(5)
plt.figure(0)
plt.plot(x, y)
z = np.sin(x)
plt.figure(1)
plt.plot(x, z)
w = np.cos(x)
plt.figure(0) # Here's the part I need
plt.plot(x, w)
Edit: Note that you can number the plots however you want (here, starting from 0
) but if you don't provide figure with a number at all when you create a new one, the automatic numbering will start at 1
("Matlab Style" according to the docs).
Appears to be resolved by Android Studio 3.0 Canary 4 and Gradle 3.0.0-alpha4.
For Mac - Opens in Chrome - Tested on VS Code v 1.9.0
Type in Configure Task Runner, the first time you do this, VS Code will give you the scroll down menu, if it does select "Other." If you have done this before, VS Code will just send you directly to tasks.json.
Once in the tasks.json file. Delete the script displayed and replace it by the following:
{ "version": "0.1.0", "command": "Chrome", "osx": { "command": "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" }, "args": ["${file}"] }
So for today, jspdf-1.5.3. To answer the question of having the pdf file page exactly same as the canvas. After many tries of different combinations, I figured you gotta do something like this. We first need to set the height and width for the output pdf file with correct orientation, otherwise the sides might be cut off. Then we get the dimensions from the 'pdf' file itself, if you tried to use the canvas's dimensions, the sides might be cut off again. I am not sure why that happens, my best guess is the jsPDF convert the dimensions in other units in the library.
// Download button
$("#download-image").on('click', function () {
let width = __CANVAS.width;
let height = __CANVAS.height;
//set the orientation
if(width > height){
pdf = new jsPDF('l', 'px', [width, height]);
}
else{
pdf = new jsPDF('p', 'px', [height, width]);
}
//then we get the dimensions from the 'pdf' file itself
width = pdf.internal.pageSize.getWidth();
height = pdf.internal.pageSize.getHeight();
pdf.addImage(__CANVAS, 'PNG', 0, 0,width,height);
pdf.save("download.pdf");
});
Learnt about switching orientations from here: https://github.com/MrRio/jsPDF/issues/476
I normally use the HttpPostedFileBase parameter only in Mvc Controllers. When dealing with ApiControllers try checking the HttpContext.Current.Request.Files property for incoming files instead:
[HttpPost]
public string UploadFile()
{
var file = HttpContext.Current.Request.Files.Count > 0 ?
HttpContext.Current.Request.Files[0] : null;
if (file != null && file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(
HttpContext.Current.Server.MapPath("~/uploads"),
fileName
);
file.SaveAs(path);
}
return file != null ? "/uploads/" + file.FileName : null;
}
From Popcorn time android app's source code I found this solution which dynamically adjusts size of viewpager with nice animation depending on the size of current child.
public class WrappingViewPager extends ViewPager {
private Boolean mAnimStarted = false;
public WrappingViewPager(Context context) {
super(context);
}
public WrappingViewPager(Context context, AttributeSet attrs){
super(context, attrs);
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
if(!mAnimStarted && null != getAdapter()) {
int height = 0;
View child = ((FragmentPagerAdapter) getAdapter()).getItem(getCurrentItem()).getView();
if (child != null) {
child.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
height = child.getMeasuredHeight();
if (VersionUtils.isJellyBean() && height < getMinimumHeight()) {
height = getMinimumHeight();
}
}
// Not the best place to put this animation, but it works pretty good.
int newHeight = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
if (getLayoutParams().height != 0 && heightMeasureSpec != newHeight) {
final int targetHeight = height;
final int currentHeight = getLayoutParams().height;
final int heightChange = targetHeight - currentHeight;
Animation a = new Animation() {
@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
if (interpolatedTime >= 1) {
getLayoutParams().height = targetHeight;
} else {
int stepHeight = (int) (heightChange * interpolatedTime);
getLayoutParams().height = currentHeight + stepHeight;
}
requestLayout();
}
@Override
public boolean willChangeBounds() {
return true;
}
};
a.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
mAnimStarted = true;
}
@Override
public void onAnimationEnd(Animation animation) {
mAnimStarted = false;
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
a.setDuration(1000);
startAnimation(a);
mAnimStarted = true;
} else {
heightMeasureSpec = newHeight;
}
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
You'll want to add a Symbolic Breakpoint
. Apple provides an excellent guide on how to do this.
cmd+7
(cmd+8
in Xcode 9)Add
button in the lower leftAdd Symbolic Breakpoint...
Symbol
just type in UIViewAlertForUnsatisfiableConstraints
You can also treat it like any other breakpoint, turning it on and off, adding actions, or log messages.
If you mean that you want to enable the submit after the user has typed at least one character, then you need to attach a key event that will check it for you.
Something like:
$("#fbss").keypress(function() {
if($(this).val().length > 1) {
// Enable submit button
} else {
// Disable submit button
}
});
I can't comment because my reputation is not high enough. @Franklin Rivero if you are using Laravel 5.2 you can set the bindings on the main query instead of the join using the setBindings method.
So the main query in @ph4r05's answer would look something like this:
$q = DnsResult::query()
->from($dnsTable . ' AS s')
->join(
DB::raw('(' . $qqSql. ') AS ss'),
function(JoinClause $join) {
$join->on('s.watch_id', '=', 'ss.watch_id')
->on('s.last_scan_at', '=', 'ss.last_scan');
})
->setBindings($subq->getBindings());
Please look into Von Pookie's answer, all credits to him/her.
Sub asdf()
Dim ws As Worksheet, newWb As Workbook
Application.ScreenUpdating = False
For Each ws In Sheets(Array("EID Upload", "Wages with Locals Upload", "Wages without Local Upload"))
ws.Copy
Set newWb = ActiveWorkbook
With newWb
.SaveAs ws.Name, xlCSV
.Close (False)
End With
Next ws
Application.ScreenUpdating = True
End Sub
In Sequelize version 5 you might also can use this way (full use Operator Sequelize) :
var condition =
{
[Op.or]: [
{
LastName: {
[Op.eq]: "Doe"
},
},
{
FirstName: {
[Op.or]: ["John", "Jane"]
}
},
{
Age:{
[Op.gt]: 18
}
}
]
}
And then, you must include this :
const Op = require('Sequelize').Op
and pass it in :
Student.findAll(condition)
.success(function(students){
//
})
It could beautifully generate SQL like this :
"SELECT * FROM Student WHERE LastName='Doe' OR FirstName in ("John","Jane") OR Age>18"
You can use Array.push()
for appending elements to an array.
For deleting, it is best to use this.$delete(array, index)
for reactive objects.
Vue.delete( target, key )
: Delete a property on an object. If the object is reactive, ensure the deletion triggers view updates. This is primarily used to get around the limitation that Vue cannot detect property deletions, but you should rarely need to use it.
Give correct maven setting.xml path in eclipse.
Enter correct setting.xml path in user settings text box
In order to encode +
value using JavaScript, you can use encodeURIComponent
function.
Example:
var url = "+11";
var encoded_url = encodeURIComponent(url);
console.log(encoded_url)
_x000D_
Here is what I use
function windowSizes(){
var e = window,
a = 'inner';
if (!('innerWidth' in window)) {
a = 'client';
e = document.documentElement || document.body;
}
return {
width: e[a + 'Width'],
height: e[a + 'Height']
};
}
$(window).on('resize', function () {
console.log( windowSizes().width,windowSizes().height );
});
with all the adjusting css. if possible, wrap it with a table with height and width as 100% and td set it to vertical align to middle, text-align to center
You could use a list comprehension:
def square(list):
return [i ** 2 for i in list]
Or you could map
it:
def square(list):
return map(lambda x: x ** 2, list)
Or you could use a generator. It won't return a list, but you can still iterate through it, and since you don't have to allocate an entire new list, it is possibly more space-efficient than the other options:
def square(list):
for i in list:
yield i ** 2
Or you can do the boring old for
-loop, though this is not as idiomatic as some Python programmers would prefer:
def square(list):
ret = []
for i in list:
ret.append(i ** 2)
return ret
You could try this
let count = s.length - s.replace(/is/g, "").length;
This isn't really recommended, but you can do it all inline like so:
<a href="#" onClick="function test(){ /* Do something */ } test(); return false;"></a>
But I can't think of any situations off hand where this would be better than writing the function somewhere else and invoking it onClick
.
I had a similar problem. I am posting my solution here because I believe it might help one of the commenters.
For me, the obstacle was that the page required a login and then gave me a new URL through javascript. Here is what I had to do:
curl -c cookiejar -g -O -J -L -F "j_username=username" -F "j_password=password" <URL>
Note that j_username
and j_password
is the name of the fields for my website's login form. You will have to open the source of the webpage to see what the 'name' of the username field and the 'name' of the password field is in your case.
After that I go an html file with java script in which the new URL was embedded. After parsing this out just resubmit with the new URL:
curl -c cookiejar -g -O -J -L -F "j_username=username" -F "j_password=password" <NEWURL>
The issue as others have stated more elegantly is that you either have a Cartesian product of the OneToMany columns or you're doing N+1 Selects. Either possible gigantic resultset or chatty with the database, respectively.
I'm surprised this isn't mentioned but this how I have gotten around this issue... I make a semi-temporary ids table. I also do this when you have the IN ()
clause limitation.
This doesn't work for all cases (probably not even a majority) but it works particularly well if you have a lot of child objects such that the Cartesian product will get out of hand (ie lots of OneToMany
columns the number of results will be a multiplication of the columns) and its more of a batch like job.
First you insert your parent object ids as batch into an ids table. This batch_id is something we generate in our app and hold onto.
INSERT INTO temp_ids
(product_id, batch_id)
(SELECT p.product_id, ?
FROM product p ORDER BY p.product_id
LIMIT ? OFFSET ?);
Now for each OneToMany
column you just do a SELECT
on the ids table INNER JOIN
ing the child table with a WHERE batch_id=
(or vice versa). You just want to make sure you order by the id column as it will make merging result columns easier (otherwise you will need a HashMap/Table for the entire result set which may not be that bad).
Then you just periodically clean the ids table.
This also works particularly well if the user selects say 100 or so distinct items for some sort of bulk processing. Put the 100 distinct ids in the temporary table.
Now the number of queries you are doing is by the number of OneToMany columns.
see this is pure css bases dropdown menu:-
HTML
<ul id="menu">
<li><a href="">Home</a></li>
<li><a href="">About Us</a>
<ul>
<li><a href="">The Team</a></li>
<li><a href="">History</a></li>
<li><a href="">Vision</a></li>
</ul>
</li>
<li><a href="">Products</a>
<ul>
<li><a href="">Cozy Couch</a></li>
<li><a href="">Great Table</a></li>
<li><a href="">Small Chair</a></li>
<li><a href="">Shiny Shelf</a></li>
<li><a href="">Invisible Nothing</a></li>
</ul>
</li>
<li><a href="">Contact</a>
<ul>
<li><a href="">Online</a></li>
<li><a href="">Right Here</a></li>
<li><a href="">Somewhere Else</a></li>
</ul>
</li>
</ul>
CSS
ul
{
font-family: Arial, Verdana;
font-size: 14px;
margin: 0;
padding: 0;
list-style: none;
}
ul li
{
display: block;
position: relative;
float: left;
}
li ul
{
display: none;
}
ul li a
{
display: block;
text-decoration: none;
color: #ffffff;
border-top: 1px solid #ffffff;
padding: 5px 15px 5px 15px;
background: #2C5463;
margin-left: 1px;
white-space: nowrap;
}
ul li a:hover
{
background: #617F8A;
}
li:hover ul
{
display: block;
position: absolute;
}
li:hover li
{
float: none;
font-size: 11px;
}
li:hover a
{
background: #617F8A;
}
li:hover li a:hover
{
background: #95A9B1;
}
see the demo:- http://jsfiddle.net/XPE3w/7/
This is a long post, but I was tired of all these examples that weren't working for me because they used Promise objects or an errant this
that has a different meaning when you are using Reactjs. My implementation was using a DropZone with reactjs, and I got the bytes using a framework similar to what is posted at this following site, when nothing else above would work: https://www.mokuji.me/article/drop-upload-tutorial-1 . There were 2 keys, for me:
I tried various combinations, but in the end, what worked was:
const bytes = e.target.result.split('base64,')[1];
Where e
is the event. React requires const
, you could use var
in plain Javascript. But that gave me the base64 encoded byte string.
So I'm just going to include the applicable lines for integrating this as if you were using React, because that's how I was building it, but try to also generalize this, and add comments where necessary, to make it applicable to a vanilla Javascript implementation - caveated that I did not use it like that in such a construct to test it.
These would be your bindings at the top, in your constructor, in a React framework (not relevant to a vanilla Javascript implementation):
this.uploadFile = this.uploadFile.bind(this);
this.processFile = this.processFile.bind(this);
this.errorHandler = this.errorHandler.bind(this);
this.progressHandler = this.progressHandler.bind(this);
And you'd have onDrop={this.uploadFile}
in your DropZone element. If you were doing this without React, this is the equivalent of adding the onclick event handler you want to run when you click the "Upload File" button.
<button onclick="uploadFile(event);" value="Upload File" />
Then the function (applicable lines... I'll leave out my resetting my upload progress indicator, etc.):
uploadFile(event){
// This is for React, only
this.setState({
files: event,
});
console.log('File count: ' + this.state.files.length);
// You might check that the "event" has a file & assign it like this
// in vanilla Javascript:
// var files = event.target.files;
// if (!files && files.length > 0)
// files = (event.dataTransfer ? event.dataTransfer.files :
// event.originalEvent.dataTransfer.files);
// You cannot use "files" as a variable in React, however:
const in_files = this.state.files;
// iterate, if files length > 0
if (in_files.length > 0) {
for (let i = 0; i < in_files.length; i++) {
// use this, instead, for vanilla JS:
// for (var i = 0; i < files.length; i++) {
const a = i + 1;
console.log('in loop, pass: ' + a);
const f = in_files[i]; // or just files[i] in vanilla JS
const reader = new FileReader();
reader.onerror = this.errorHandler;
reader.onprogress = this.progressHandler;
reader.onload = this.processFile(f);
reader.readAsDataURL(f);
}
}
}
There was this question on that syntax, for vanilla JS, on how to get that file object:
Note that React's DropZone will already put the File object into this.state.files
for you, as long as you add files: [],
to your this.state = { .... }
in your constructor. I added syntax from an answer on that post on how to get your File object. It should work, or there are other posts there that can help. But all that Q/A told me was how to get the File
object, not the blob data, itself. And even if I did fileData = new Blob([files[0]]);
like in sebu's answer, which didn't include var
with it for some reason, it didn't tell me how to read that blob's contents, and how to do it without a Promise object. So that's where the FileReader came in, though I actually tried and found I couldn't use their readAsArrayBuffer
to any avail.
You will have to have the other functions that go along with this construct - one to handle onerror
, one for onprogress
(both shown farther below), and then the main one, onload
, that actually does the work once a method on reader
is invoked in that last line. Basically you are passing your event.dataTransfer.files[0]
straight into that onload
function, from what I can tell.
So the onload
method calls my processFile()
function (applicable lines, only):
processFile(theFile) {
return function(e) {
const bytes = e.target.result.split('base64,')[1];
}
}
And bytes
should have the base64 bytes.
Additional functions:
errorHandler(e){
switch (e.target.error.code) {
case e.target.error.NOT_FOUND_ERR:
alert('File not found.');
break;
case e.target.error.NOT_READABLE_ERR:
alert('File is not readable.');
break;
case e.target.error.ABORT_ERR:
break; // no operation
default:
alert('An error occurred reading this file.');
break;
}
}
progressHandler(e) {
if (e.lengthComputable){
const loaded = Math.round((e.loaded / e.total) * 100);
let zeros = '';
// Percent loaded in string
if (loaded >= 0 && loaded < 10) {
zeros = '00';
}
else if (loaded < 100) {
zeros = '0';
}
// Display progress in 3-digits and increase bar length
document.getElementById("progress").textContent = zeros + loaded.toString();
document.getElementById("progressBar").style.width = loaded + '%';
}
}
And applicable progress indicator markup:
<table id="tblProgress">
<tbody>
<tr>
<td><b><span id="progress">000</span>%</b> <span className="progressBar"><span id="progressBar" /></span></td>
</tr>
</tbody>
</table>
And CSS:
.progressBar {
background-color: rgba(255, 255, 255, .1);
width: 100%;
height: 26px;
}
#progressBar {
background-color: rgba(87, 184, 208, .5);
content: '';
width: 0;
height: 26px;
}
EPILOGUE:
Inside processFile()
, for some reason, I couldn't add bytes
to a variable I carved out in this.state
. So, instead, I set it directly to the variable, attachments
, that was in my JSON object, RequestForm
- the same object as my this.state
was using. attachments
is an array so I could push multiple files. It went like this:
const fileArray = [];
// Collect any existing attachments
if (RequestForm.state.attachments.length > 0) {
for (let i=0; i < RequestForm.state.attachments.length; i++) {
fileArray.push(RequestForm.state.attachments[i]);
}
}
// Add the new one to this.state
fileArray.push(bytes);
// Update the state
RequestForm.setState({
attachments: fileArray,
});
Then, because this.state
already contained RequestForm
:
this.stores = [
RequestForm,
]
I could reference it as this.state.attachments
from there on out. React feature that isn't applicable in vanilla JS. You could build a similar construct in plain JavaScript with a global variable, and push, accordingly, however, much easier:
var fileArray = new Array(); // place at the top, before any functions
// Within your processFile():
var newFileArray = [];
if (fileArray.length > 0) {
for (var i=0; i < fileArray.length; i++) {
newFileArray.push(fileArray[i]);
}
}
// Add the new one
newFileArray.push(bytes);
// Now update the global variable
fileArray = newFileArray;
Then you always just reference fileArray
, enumerate it for any file byte strings, e.g. var myBytes = fileArray[0];
for the first file.
One part missing in all these explanations is how are Cookies and Session linked- By SessionID cookie. Cookie goes back and forth between client and server - the server links the user (and its session) by session ID portion of the cookie. You can send SessionID via url also (not the best best practice) - in case cookies are disabled by client.
Did I get this right?
div.section > div
Following @Francisco Goldenstein answer, I wrote an extension method
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
namespace Mediatel.Framework
{
public static class XDocumentHelper
{
public static IEnumerable<XElement> DescendantElements(this XDocument xDocument, string nodeName)
{
return xDocument.Descendants().Where(p => p.Name.LocalName == nodeName);
}
}
}
Catching an exception while using a Python 'with' statement
The with statement has been available without the __future__
import since Python 2.6. You can get it as early as Python 2.5 (but at this point it's time to upgrade!) with:
from __future__ import with_statement
Here's the closest thing to correct that you have. You're almost there, but with
doesn't have an except
clause:
with open("a.txt") as f: print(f.readlines()) except: # <- with doesn't have an except clause. print('oops')
A context manager's __exit__
method, if it returns False
will reraise the error when it finishes. If it returns True
, it will suppress it. The open
builtin's __exit__
doesn't return True
, so you just need to nest it in a try, except block:
try:
with open("a.txt") as f:
print(f.readlines())
except Exception as error:
print('oops')
And standard boilerplate: don't use a bare except:
which catches BaseException
and every other possible exception and warning. Be at least as specific as Exception
, and for this error, perhaps catch IOError
. Only catch errors you're prepared to handle.
So in this case, you'd do:
>>> try:
... with open("a.txt") as f:
... print(f.readlines())
... except IOError as error:
... print('oops')
...
oops
You can use jQuery bind:
$(window).bind('keydown', function(e){
if (e.keyCode == 37) {
console.log('left');
} else if (e.keyCode == 38) {
console.log('up');
} else if (e.keyCode == 39) {
console.log('right');
} else if (e.keyCode == 40) {
console.log('down');
}
});
If you want to leave only numbers - use preg_replace like: (int)preg_replace("/[^\d]+/","",$b).
You can use Comparator.reverseOrder()
to have a comparator giving the reverse of the natural ordering.
If you want to reverse the ordering of an existing comparator, you can use Comparator.reversed()
.
Sample code:
Stream.of(1, 4, 2, 5)
.sorted(Comparator.reverseOrder());
// stream is now [5, 4, 2, 1]
Stream.of("foo", "test", "a")
.sorted(Comparator.comparingInt(String::length).reversed());
// stream is now [test, foo, a], sorted by descending length
If you using java-based annotation you can do this:
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**").addResourceLocations("/static/");
}
Where static folder
src
¦
+---main
+---java
+---resources
+---webapp
+---static
+---css
+---....
but do you not just get your combo box name and then items.add("")
?
For instance
Language.Items.Add("Italian");
Language.Items.Add("English");
Language.Items.Add("Spanish");
Hope this helped :D
You can use a bucket policy to give anonymous users full read access to your objects. Depending on whether you need them to LIST or just perform a GET, you'll want to tweak this. (I.e. permissions for listing the contents of a bucket have the action set to "s3:ListBucket").
http://docs.aws.amazon.com/AmazonS3/latest/dev/AccessPolicyLanguage_UseCases_s3_a.html
Your policy will look something like the following. You can use the S3 console at http://aws.amazon.com/console to upload it.
{
"Version":"2008-10-17",
"Statement":[{
"Sid":"AddPerm",
"Effect":"Allow",
"Principal": {
"AWS": "*"
},
"Action":["s3:GetObject"],
"Resource":["arn:aws:s3:::bucket/*"
]
}
]
}
If you're truly opening up your objects to the world, you'll want to look into setting up CloudWatch rules on your billing so you can shut off permissions to your objects if they become too popular.
This is not mentioned in you post but I suspect you are initiating an SSL connection from the browser to Apache, where VirtualHosts are configured, and Apache does a revese proxy to your Tomcat.
There is a serious bug in (some versions ?) of IE that sends the 'wrong' host information in an SSL connection (see EDIT below) and confuses the Apache VirtualHosts. In short the server name presented is the one of the reverse DNS resolution of the IP, not the one in the URL.
The workaround is to have one IP address per SSL virtual hosts/server name. Is short, you must end up with something like
1 server name == 1 IP address == 1 certificate == 1 Apache Virtual Host
EDIT
Though the conclusion is correct, the identification of the problem is better described here http://en.wikipedia.org/wiki/Server_Name_Indication
You can catch the event and then block it with preventDefault() -- works with pure Javascript
document.getElementById("xyz").addEventListener('click', function(event){
event.preventDefault();
console.log(this.getAttribute("href"));
/* Do some other things*/
});
If you are in Chrome you can check the Post Data
Here is How to check the Post data
I don't know if this is the answer or not but it might lead you in the right direction...
The command install:install
is actually a goal on the maven-install-plugin. This is different than the install
maven lifecycle phase.
Maven lifecycle phases are steps in a build which certain plugins can bind themselves to. Many different goals from different plugins may execute when you invoke a single lifecycle phase.
What this boils down to is the command...
mvn clean install
is different from...
mvn clean install:install
The former will run all goals in every cycle leading up to and including the install (like compile, package, test, etc.). The latter will not even compile or package your code, it will just run that one goal. This kinda makes sense, looking at the exception; it talks about:
StarTeamCollisionUtil: The packaging for this project did not assign a file to the build artifact
Try the former and your error might just go away!
If you want to update / add single style in DOM Element style attribute you can use this function:
function setCssTextStyle(el, style, value) {
var result = el.style.cssText.match(new RegExp("(?:[;\\s]|^)(" +
style.replace("-", "\\-") + "\\s*:(.*?)(;|$))")),
idx;
if (result) {
idx = result.index + result[0].indexOf(result[1]);
el.style.cssText = el.style.cssText.substring(0, idx) +
style + ": " + value + ";" +
el.style.cssText.substring(idx + result[1].length);
} else {
el.style.cssText += " " + style + ": " + value + ";";
}
}
style.cssText is supported for all major browsers.
Use case example:
var elem = document.getElementById("elementId");
setCssTextStyle(elem, "margin-top", "10px !important");
This is simple but the developer gets confused due to multiple views having the same attributes in different configurations/namespaces.
In the case of the TextInputLayout we have every time a different view and with params either with TextInputEditText or directly to TextInputLayout.
I was using all the above fixes: But I found that I was using
app:textColorHint="@color/textcolor_black"
actually i should be using
android:textColorHint="@color/textcolor_black"
As an attribute of TextinputLayout
textcolor_black.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="@color/black_txt" android:state_enabled="true" />
<item android:color="@color/black_txt" android:state_selected="true" />
<item android:color="@color/txtColorGray" android:state_selected="false" />
<item android:color="@color/txtColorGray" android:state_enabled="false" />
</selector>
This is standards compliant and cross-browser safe.
Example: http://jsfiddle.net/kv9pw/
var span = document.getElementById('someID');
while( span.firstChild ) {
span.removeChild( span.firstChild );
}
span.appendChild( document.createTextNode("some new content") );
according to JAVA documentation, the JDK should be installed in this path:
/Library/Java/JavaVirtualMachines/jdkmajor.minor.macro[_update].jdk
See the uninstall JDK part at https://docs.oracle.com/javase/8/docs/technotes/guides/install/mac_jdk.html
So if you can find such folder then the JDK is installed
i used replace feature in Notepad++ and replaced "
(without quotes) with "
and result was valid json
Is this what you are after? Just index the element and assign a new value.
A[2,1]=150
A
Out[345]:
array([[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9, 150, 11, 12],
[13, 14, 15, 16]])
One solution could be to wrap the options inside optgroup:
optgroup { font-size:40px; }
_x000D_
<select>
<optgroup>
<option selected="selected" class="service-small">Service area?</option>
<option class="service-small">Volunteering</option>
<option class="service-small">Partnership & Support</option>
<option class="service-small">Business Services</option>
</optgroup>
</select>
_x000D_
This has not been tested but I think this should work using mod_rewrite
RewriteEngine On
RewriteCond %{HTTPS} on
RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI}
Combining @Joachim's with the above, you could use
next(iter(my_list[index:index+1]), default)
Examples:
next(iter(range(10)[8:9]), 11)
8
>>> next(iter(range(10)[12:13]), 11)
11
Or, maybe more clear, but without the len
my_list[index] if my_list[index:index + 1] else default
You're checking if the result of IndexOf is larger or equal 0, meaning whether the match starts anywhere in the string. Try checking if it's equal to 0:
if (testList.FindAll(x => x.IndexOf(keyword,
StringComparison.OrdinalIgnoreCase) >= 0).Count > 0)
Console.WriteLine("Found in list");
Now "goat" and "oat" won't match, but "goat" and "goa" will. To avoid this, you can compare the lenghts of the two strings.
To avoid all this complication, you can use a dictionary instead of a list. They key would be the lowercase string, and the value would be the real string. This way, performance isn't hurt because you don't have to use ToLower
for each comparison, but you can still use Contains
.
I didn't want to install a package just for that purpose so I ended up using this in my init.coffee
:
spawn = require('child_process').spawn
atom.commands.add 'atom-text-editor', 'open-terminal', ->
file = atom.workspace.getActiveTextEditor().getPath()
dir = atom.project.getDirectoryForProjectPath(file).path
spawn 'mate-terminal', ["--working-directory=#{dir}"], {
detached: true
}
With that, I could map ctrl-shift-t
to the open-terminal
command and it opens a mate-terminal.
If you are using Java 8+ and need a 2 dimensional Array
, perhaps for TestNG data providers, you can try:
map.entrySet()
.stream()
.map(e -> new Object[]{e.getKey(), e.getValue()})
.toArray(Object[][]::new);
If your Object
s are String
s and you need a String[][]
, try:
map.entrySet()
.stream()
.map(e -> new String[]{e.getKey(), e.getValue().toString()})
.toArray(String[][]::new);
Simpler way would be
$mystring = json_encode($my_json,JSON_UNESCAPED_SLASHES);
Python uses the :: to separate the End, the Start, and the Step value.
I had the same problem, tnsnames.ora
worked fine for all other tools but SQL Developer would not use it. I tried all the suggestions on the web I could find, including the solutions on the link provided here.
Nothing worked.
It turns out that the database was caching backup copies of tnsnames.ora
like tnsnames.ora.bk2
, tnsnames09042811AM4501.bak
, tnsnames.ora.bk
etc. These files were not readable by the average user.
I suspect sqldeveloper is pattern matching for the name and it was trying to read one of these backup copies and couldn't. So it just fails gracefully and shows nothing in drop down list.
The solution is to make all the files readable or delete or move the backup copies out of the Admin directory.
java.io.IOException: Connection reset by peer
In my case, the problem was with PUT requests (GET and POST were passing successfully).
Communication went through VPN tunnel and ssh connection. And there was a firewall with default restrictions on PUT requests... PUT requests haven't been passing throughout, to the server...
Problem was solved after exception was added to the firewall for my IP address.
I checked quite some links for the solution, finally did the below mentioned steps to get it working. I am using Gradle 2.9.
Make the following changes in your build,gradle file :
Mention plugin:
apply plugin: 'eu.appsatori.fatjar'
Provide the Buildscript:
buildscript {
repositories {
jcenter()
}
dependencies {
classpath "eu.appsatori:gradle-fatjar-plugin:0.3"
}
}
Provide the Main Class:
fatJar {
classifier 'fat'
manifest {
attributes 'Main-Class': 'my.project.core.MyMainClass'
}
exclude 'META-INF/*.DSA', 'META-INF/*.RSA', 'META-INF/*.SF'
}
Create the fatjar:
./gradlew clean fatjar
Run the fatjar from /build/libs/ :
java -jar MyFatJar.jar
i install mysql for visual studio and the problem simply solved.although version of my visual studio is 2012!
the first time when you are returning your form make sure you pass the model attribute the form requires which can be done by adding the below code
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String login(Login login)
return "test";
}
By default the model attribute name is taken as Bean class's name with first lowercase letter
By doing this the form which expects a backing object naming "login" will be made available to it
after the form is submitted you can do the validation by passing your bean object and bindingresult as the method parameters as shown below
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String login( @ModelAttribute("login") Login login,
BindingResult result)
This one was a hard nut to crack, so for the record:
To solve this, it required a custom KeyManager
and a SSLSocketFactory
that uses this custom KeyManager
to access the separated KeyStore
.
I found the base code for this KeyStore
and SSLFactory
on this excellent blog entry:
how-to-dynamically-select-a-certificate-alias-when-invoking-web-services
Then, the specialized SSLSocketFactory
needs to be inserted into the WebService context:
service = getWebServicePort(getWSDLLocation());
BindingProvider bindingProvider = (BindingProvider) service;
bindingProvider.getRequestContext().put("com.sun.xml.internal.ws.transport.https.client.SSLSocketFactory", getCustomSocketFactory());
Where the getCustomSocketFactory()
returns a SSLSocketFactory
created using the method mentioned above. This would only work for JAX-WS RI from the Sun-Oracle impl built into the JDK, given that the string indicating the SSLSocketFactory
property is proprietary for this implementation.
At this stage, the JAX-WS service communication is secured through SSL, but if you are loading the WSDL from the same secure server () then you'll have a bootstrap problem, as the HTTPS request to gather the WSDL will not be using the same credentials than the Web Service. I worked around this problem by making the WSDL locally available (file:///...) and dynamically changing the web service endpoint: (a good discussion on why this is needed can be found in this forum)
bindingProvider.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, webServiceLocation);
Now the WebService gets bootstrapped and is able to communicate through SSL with the server counterpart using a named (alias) Client-Certificate and mutual authentication. ?
overflow:hidden
and padding-left
are working fine for me.
For Firefox:
width:12px;
height:20px;
background-image:url(images/arrow.gif);
color:transparent;
overflow:hidden;
border:0;
For the IEs:
padding-left:1000px;
Simply You can do
SELECT DATE(date_field) AS date_field FROM table_name
You can use npm i y-websockets-server
and then use the below command
y-websockets-server --port 11000
and here in my case, the port No is 11000.
$http
service returns a promise
which has two callback methods as shown below.
$http({method: 'GET', url: '/someUrl'}).
success(function(data, status, headers, config) {
var anchor = angular.element('<a/>');
anchor.attr({
href: 'data:attachment/csv;charset=utf-8,' + encodeURI(data),
target: '_blank',
download: 'filename.csv'
})[0].click();
}).
error(function(data, status, headers, config) {
// handle error
});