kubectl get nodes
Result:
NAME STATUS AGE
192.168.1.157 NotReady 42d
192.168.1.158 Ready 42d
192.168.1.159 Ready 42d
Here is a NotReady on the node of 192.168.1.157
. Then debugging this notready node, and you can read offical documents - Application Introspection and Debugging.
kubectl describe node 192.168.1.157
Partial Result:
Conditions:
Type Status LastHeartbeatTime LastTransitionTime Reason Message
---- ------ ----------------- ------------------ ------ -------
OutOfDisk Unknown Sat, 28 Dec 2016 12:56:01 +0000 Sat, 28 Dec 2016 12:56:41 +0000 NodeStatusUnknown Kubelet stopped posting node status.
Ready Unknown Sat, 28 Dec 2016 12:56:01 +0000 Sat, 28 Dec 2016 12:56:41 +0000 NodeStatusUnknown Kubelet stopped posting node status.
There is a OutOfDisk on my node, then Kubelet stopped posting node status.
So, I must free some disk space, using the command of df
on my Ubuntu14.04 I can check the details of memory, and using the command of docker rmi image_id/image_name
under the role of su
I can remove the useless images.
Login in 192.168.1.157
by using ssh, like ssh [email protected]
, and switch to the 'su' by sudo su
;
/etc/init.d/kubelet restart
Result:
stop: Unknown instance:
kubelet start/running, process 59261
On the master:
kubectl get nodes
Result:
NAME STATUS AGE
192.168.1.157 Ready 42d
192.168.1.158 Ready 42d
192.168.1.159 Ready 42d
Ok, that node works fine.
Here is a reference: Kubernetes
You can use urllib2
import urllib2
content = urllib2.urlopen(some_url).read()
print content
Also you can use httplib
import httplib
conn = httplib.HTTPConnection("www.python.org")
conn.request("HEAD","/index.html")
res = conn.getresponse()
print res.status, res.reason
# Result:
200 OK
or the requests library
import requests
r = requests.get('https://api.github.com/user', auth=('user', 'pass'))
r.status_code
# Result:
200
source: this post
if you created your elements dynamically(using javascript), then this code doesn't work. Because, .click() will attach events to elements that already exists. As you are dynamically creating your elements using javascript, it doesn't work.
For this you have to use some other functions which works on dynamically created elements. This can be done in different ways..
Earlier we have .live() function
$('selector').live('click', function()
{
//your code
});
but .live() is deprecated.This can be replaced by other functions.
Delegate():
Using delegate() function you can click on dynamically generated HTML elements.
Example:
$(document).delegate('selector', 'click', function()
{
//your code
});
EDIT: The delegate() method was deprecated in version 3.0. Use the on() method instead.
ON():
Using on() function you can click on dynamically generated HTML elements.
Example:
$(document).on('click', 'selector', function()
{
// your code
});
string stringtodate = ((DateTime)row.Cells[4].Value).ToString("MM-dd-yyyy");
textBox9.Text = stringtodate;
The first error
java.lang.Exception; must be caught or declared to be thrown byte[] encrypted = encrypt(concatURL);
means that your encrypt
method throws an exception that is not being handled or declared by the actionPerformed
method where you are calling it. Read all about it at the Java Exceptions Tutorial.
You have a couple of choices that you can pick from to get the code to compile.
throws Exception
from your encrypt
method and actually handle the exception inside encrypt
.encrypt
and add throws Exception
and the exception handling block to your actionPerformed
method.It's generally better to handle an exception at the lowest level that you can, instead of passing it up to a higher level.
The second error just means that you need to add a return statement to whichever method contains line 109 (also encrypt
, in this case). There is a return statement in the method, but if an exception is thrown it might not be reached, so you either need to return in the catch block, or remove the try/catch from encrypt
, as I mentioned before.
public class DrawableCenterTextView extends TextView {
public DrawableCenterTextView(Context context, AttributeSet attrs,
int defStyle) {
super(context, attrs, defStyle);
}
public DrawableCenterTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public DrawableCenterTextView(Context context) {
super(context);
}
@Override
protected void onDraw(Canvas canvas) {
Drawable[] drawables = getCompoundDrawables();
if (drawables != null) {
Drawable drawableLeft = drawables[0];
Drawable drawableRight = drawables[2];
if (drawableLeft != null || drawableRight != null) {
float textWidth = getPaint().measureText(getText().toString());
int drawablePadding = getCompoundDrawablePadding();
int drawableWidth = 0;
if (drawableLeft != null)
drawableWidth = drawableLeft.getIntrinsicWidth();
else if (drawableRight != null) {
drawableWidth = drawableRight.getIntrinsicWidth();
}
float bodyWidth = textWidth + drawableWidth + drawablePadding;
canvas.translate((getWidth() - bodyWidth) / 2, 0);
}
}
super.onDraw(canvas);
}
}
None of these methods worked for me in .NET Core 2.2 but I was able to adapt some code I had for defining a different primary key to work for this purpose.
In the instance below I want to ensure the OutletRef field is unique:
public class ApplicationDbContext : IdentityDbContext
{
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Outlet>()
.HasIndex(o => new { o.OutletRef });
}
}
This adds the required unique index in the database. What it doesn't do though is provide the ability to specify a custom error message.
click appears to be blocking? - here's another way to wait if you're using WebDriverJS:
driver.findElement(webdriver.By.name('mybutton')).click().then(function(){
driver.getPageSource().then(function(source) {
console.log(source);
});
});
The code above waits after the button is clicked for the next page to load and then grabs the source of the next page.
You can also send (POST
) multiple params within {}
and add it.
Example:
$http.post(config.url+'/api/assign-badge/', {employeeId:emp_ID,bType:selectedCat,badge:selectedBadge})
.then(function(response) {
NotificationService.displayNotification('Info', 'Successfully Assigned!', true);
}, function(response) {
});
where employeeId
, bType
(Badge Catagory), and badge
are three parameters.
I also had to setup connection to 2 datasources from Spring Boot application, and it was not easy - the solution mentioned in the Spring Boot documentation didn't work. After a long digging through the internet I made it work and the main idea was taken from this article and bunch of other places.
The following solution is written in Kotlin and works with Spring Boot 2.1.3 and Hibernate Core 5.3.7. Main issue was that it was not enough just to setup different DataSource configs, but it was also necessary to configure EntityManagerFactory and TransactionManager for both databases.
Here is config for the first (Primary) database:
@Configuration
@EnableJpaRepositories(
entityManagerFactoryRef = "firstDbEntityManagerFactory",
transactionManagerRef = "firstDbTransactionManager",
basePackages = ["org.path.to.firstDb.domain"]
)
@EnableTransactionManagement
class FirstDbConfig {
@Bean
@Primary
@ConfigurationProperties(prefix = "spring.datasource.firstDb")
fun firstDbDataSource(): DataSource {
return DataSourceBuilder.create().build()
}
@Primary
@Bean(name = ["firstDbEntityManagerFactory"])
fun firstDbEntityManagerFactory(
builder: EntityManagerFactoryBuilder,
@Qualifier("firstDbDataSource") dataSource: DataSource
): LocalContainerEntityManagerFactoryBean {
return builder
.dataSource(dataSource)
.packages(SomeEntity::class.java)
.persistenceUnit("firstDb")
// Following is the optional configuration for naming strategy
.properties(
singletonMap(
"hibernate.naming.physical-strategy",
"org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl"
)
)
.build()
}
@Primary
@Bean(name = ["firstDbTransactionManager"])
fun firstDbTransactionManager(
@Qualifier("firstDbEntityManagerFactory") firstDbEntityManagerFactory: EntityManagerFactory
): PlatformTransactionManager {
return JpaTransactionManager(firstDbEntityManagerFactory)
}
}
And this is config for second database:
@Configuration
@EnableJpaRepositories(
entityManagerFactoryRef = "secondDbEntityManagerFactory",
transactionManagerRef = "secondDbTransactionManager",
basePackages = ["org.path.to.secondDb.domain"]
)
@EnableTransactionManagement
class SecondDbConfig {
@Bean
@ConfigurationProperties("spring.datasource.secondDb")
fun secondDbDataSource(): DataSource {
return DataSourceBuilder.create().build()
}
@Bean(name = ["secondDbEntityManagerFactory"])
fun secondDbEntityManagerFactory(
builder: EntityManagerFactoryBuilder,
@Qualifier("secondDbDataSource") dataSource: DataSource
): LocalContainerEntityManagerFactoryBean {
return builder
.dataSource(dataSource)
.packages(EntityFromSecondDb::class.java)
.persistenceUnit("secondDb")
.build()
}
@Bean(name = ["secondDbTransactionManager"])
fun secondDbTransactionManager(
@Qualifier("secondDbEntityManagerFactory") secondDbEntityManagerFactory: EntityManagerFactory
): PlatformTransactionManager {
return JpaTransactionManager(secondDbEntityManagerFactory)
}
}
The properties for datasources are like this:
spring.datasource.firstDb.jdbc-url=
spring.datasource.firstDb.username=
spring.datasource.firstDb.password=
spring.datasource.secondDb.jdbc-url=
spring.datasource.secondDb.username=
spring.datasource.secondDb.password=
Issue with properties was that I had to define jdbc-url instead of url because otherwise I had an exception.
p.s. Also you might have different naming schemes in your databases, which was the case for me. Since Hibernate 5 does not support all previous naming schemes, I had to use solution from this answer - maybe it will also help someone as well.
Most likely, as mentioned by others, it is a class carrying the css values:
.clear{clear: both;}
in order to prevent any more page elements from extending into the footer element. It is a quick and easy way of making sure that pages with columns of varying heights don't cause the footer to render oddly, by possibly setting its top position at the end of a shorter column.
In many cases it is not necessary, but if you are using best-practice standards it is a good idea to use, if you are floating page elements left and right. It functions with page elements similar to the way a horizontal rule works with text, to ensure proper and complete sepperation.
in the facebook App Page, goto the basic tab. find "Website with Facebook Login" Option.
you will find Site URL: input there put the full URL ( for example http://Mywebsite.com/MyLogin.aspx ). this is the URL you can use with the call like If the APP ID is 123456789
If the class implements comparable, you could also do
int compRes = a.compareTo(b);
if(compRes < 0 || compRes > 0)
System.out.println("not equal");
else
System.out.println("equal);
doesn't use a !
, though not particularly useful, or readable....
The above method works good.
Another method (I am assuming web here) is to create your page. Add controls to the page. Then while in design mode go to: Tools > Generate Local Resource. A resource file will automatically appear in the solution with all the controls in the page mapped in the resource file.
To create resources for other languages, append the 4 character language to the end of the file name, before the extension (Account.aspx.en-US.resx, Account.aspx.es-ES.resx...etc).
To retrieve specific entries in the code-behind, simply call this method: GetLocalResourceObject([resource entry key/name])
.
You're calling nextElement twice in the loop. You should call it only once, else it moves ahead twice:
while(e.hasMoreElements()){
String s = e.nextElement();
System.out.println(s);
}
This problem can be caused also by jvm version used to compile the project and the jvm supported by the servlet container. Try to Fix the project build path. For example if you deploy on tomcat 9, use jvm 1.8.0 or lower.
Probably the easiest thing to do would be to give your scrip tag an id
attribute.
<body ng-app="app">
<button type="button" ng-click="showme==true ? !showme :showme;message='Cancel Quiz'" class="btn btn-default">{{showme==true ? 'Cancel Quiz': 'Take a Quiz'}}</button>
<div ng-show="showme" class="panel panel-primary col-sm-4" style="margin-left:250px;">
<div class="panel-heading">Take Quiz</div>
<div class="form-group col-sm-8 form-inline" style="margin-top: 30px;margin-bottom: 30px;">
<button type="button" class="btn btn-default">Start Quiz</button>
</div>
</div>
</body>
Button toggle and change header of button and show/hide div panel. See the Plunkr
This works seamlessly for me.
element.get_attribute('innerHTML')
try with this metods:
int width = mView.getMeasuredWidth();
int height = mView.getMeasuredHeight();
Or
int width = mTextView.getMeasuredWidth();
int height = mTextView.getMeasuredHeight();
This question will get moved but you can do the following
which javac
or
cd /
find . -name 'javac'
Here is a very simple way (3 lines of code) using the Fullscreen API and RequestFullscreen method that I used, which is compatible across all popular browsers:
var elem = document.getElementsByTagName('video')[0];_x000D_
var fullscreen = elem.webkitRequestFullscreen || elem.mozRequestFullScreen || elem.msRequestFullscreen;_x000D_
fullscreen.call(elem); // bind the 'this' from the video object and instantiate the correct fullscreen method.
_x000D_
Try doing this :
recipients="[email protected],[email protected],[email protected]"
And another approach, using shell here-doc :
/usr/sbin/sendmail "$recipients" <<EOF
subject:$subject
from:$from
Example Message
EOF
Be sure to separate the headers from the body with a blank line as per RFC 822.
.env
and .env.production
VUE_APP_
eg: VUE_APP_WHATEVERYOUWANT
.env
and build uses .env.production
process.env.VUE_APP_WHATEVERYOUWANT
to call valueBe sure you are using vue-cli version 3 or above
For more information: https://cli.vuejs.org/guide/mode-and-env.html
I realize that this is an old question, but I'll post the solution for my use case, in case others run into the same situation I did when implementing James Hill's answer (above).
I found this question while trying to solve the same issue. James' answer got me 90% there. However, for my use case, selecting the item from the dropdown also triggered an action on the page from dropdown's onchange
event. James' code as written did not trigger this event (at least in Firefox, which I was testing in). As a result, I made the following minor change:
function setSelectedValue(object, value) {
for (var i = 0; i < object.options.length; i++) {
if (object.options[i].text === value) {
object.options[i].selected = true;
object.onchange();
return;
}
}
// Throw exception if option `value` not found.
var tag = object.nodeName;
var str = "Option '" + value + "' not found";
if (object.id != '') {
str = str + " in //" + object.nodeName.toLowerCase()
+ "[@id='" + object.id + "']."
}
else if (object.name != '') {
str = str + " in //" + object.nodeName.toLowerCase()
+ "[@name='" + object.name + "']."
}
else {
str += "."
}
throw str;
}
Note the object.onchange()
call, which I added to the original solution. This calls the handler to make certain that the action on the page occurs.
Added code to throw an exception if option value
is not found; this is needed for my use case.
If you want to pass data to form2
from form1
without passing like new form(sting "data");
Do like that in form 1
using (Form2 form2= new Form2())
{
form2.ReturnValue1 = "lalala";
form2.ShowDialog();
}
in form 2 add
public string ReturnValue1 { get; set; }
private void form2_Load(object sender, EventArgs e)
{
MessageBox.Show(ReturnValue1);
}
Also you can use value in form1
like this if you want to swap something in form1
just in form1
textbox.Text =form2.ReturnValue1
According to this MSDN blog: https://blogs.msdn.microsoft.com/manishagarwal/2005/09/28/resolving-file-references-in-team-build-part-2/
There is a search order for assemblies when building. The search order is as follows:
So, if the desired assembly is found by HintPath, but an alternate assembly can be found using ReferencePath, it will prefer the ReferencePath'd assembly to the HintPath'd one.
Subversion does not yet have a first-class rename operations.
There's a 6-year-old bug on the problem: http://subversion.tigris.org/issues/show_bug.cgi?id=898
It's being considered for 1.6, now that merge tracking (a higher priority) has been added (in 1.5).
This is not possible with native HTML input elements. You can use webshim polyfill, which gives you this option by using this markup.
<input type="date" data-date-inline-picker="true" />
Here is a small demo
As such, it is desirable to split the dataset into train and test sets in a way that preserves the same proportions of examples in each class as observed in the original dataset.
This is called a stratified train-test split.
We can achieve this by setting the “stratify” argument to the y component of the original dataset. This will be used by the train_test_split() function to ensure that both the train and test sets have the proportion of examples in each class that is present in the provided “y” array.
You can write one liner using DataRow.Add(params object[] values) instead of four lines.
dt.Rows.Add("Ravi", "500");
As you create new DataTable
object, there seems no need to Clear
DataTable
in very next statement. You can also use DataTable.Columns.AddRange
to add columns with on statement. Complete code would be.
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[] { new DataColumn("Name"), new DataColumn("Marks") });
dt.Rows.Add("Ravi", "500");
I had the same problem but from IIS in visual studio, I went to project properties -> Web -> and project url change http to https
You'll have to pass the new ordinal position to insert
using len
in this case:
In [62]:
a=[1,2,3,4]
a.insert(len(a),5)
a
Out[62]:
[1, 2, 3, 4, 5]
Assuming you are using this plugin, you are misusing the .set
method. .set
must be passed the name of the key as a string as well as the value. I suppose you meant to write:
$.session.set("userName", $("#uname").val());
This sets the userName
key in session storage to the value of the input, and allows you to retrieve it using:
$.session.get('userName');
Here's how you can debug CORS requests using curl.
Sending a regular CORS request using cUrl:
curl -H "Origin: http://example.com" --verbose \
https://www.googleapis.com/discovery/v1/apis?fields=
The -H "Origin: http://example.com"
flag is the third party domain making the request. Substitute in whatever your domain is.
The --verbose
flag prints out the entire response so you can see the request and response headers.
The url I'm using above is a sample request to a Google API that supports CORS, but you can substitute in whatever url you are testing.
The response should include the Access-Control-Allow-Origin
header.
Sending a preflight request using cUrl:
curl -H "Origin: http://example.com" \
-H "Access-Control-Request-Method: POST" \
-H "Access-Control-Request-Headers: X-Requested-With" \
-X OPTIONS --verbose \
https://www.googleapis.com/discovery/v1/apis?fields=
This looks similar to the regular CORS request with a few additions:
The -H
flags send additional preflight request headers to the server
The -X OPTIONS
flag indicates that this is an HTTP OPTIONS request.
If the preflight request is successful, the response should include the Access-Control-Allow-Origin
, Access-Control-Allow-Methods
, and Access-Control-Allow-Headers
response headers. If the preflight request was not successful, these headers shouldn't appear, or the HTTP response won't be 200.
You can also specify additional headers, such as User-Agent
, by using the -H
flag.
pod update POD_NAME
will update latest pod but not update Podfile.lock
file.
So, you may update your Podfile with specific version of your pod e.g pod 'POD_NAME', '~> 2.9.0'
and then use command pod install
Later, you can remove the specific version naming from your Podfile and can again use pod install
. This will helps to keep Podfile.lock
updated.
You can use following code to read file in String from resource folder.
final Resource resource = new ClassPathResource("public.key");
String publicKey = null;
try {
publicKey = new String(Files.readAllBytes(resource.getFile().toPath()), StandardCharsets.UTF_8);
} catch (IOException e) {
e.printStackTrace();
}
Nowadays - using C++11 - you can use enum class for this:
enum class Color { RED, BLUE, WHITE };
AFAII this does exactly what you want.
Use %0A
(URL encoding) instead of \n
(C encoding).
jQlite (angular's "jQuery" port) doesn't support lookup by classes.
One solution would be to include jQuery in your app.
Another is using QuerySelector
or QuerySelectorAll
:
link: function(scope, element, attrs) {
console.log(element[0].querySelector('.list-scrollable'))
}
We use the first item in the element
array, which is the HTML element. element.eq(0)
would yield the same.
If you want to rollback last migration.
php artisan migrate:rollback
If you want to rollback specific migration then go to migration table and set highest value of that record in batch. Then.
php artisan migrate:rollback
Currently i'm working on laravel 5.8 if not working any other version of laravel please inform to me.
Try it.
You can just pass the path to the style sheet .
{!! HTML::style('css/style.css') !!}
You can just pass the path to the javascript.
{!! HTML::script('js/script.js') !!}
Add the following lines in the require section of composer.json file and run composer update "illuminate/html": "5.*".
Register the service provider in config/app.php by adding the following value into the providers array:
'Illuminate\Html\HtmlServiceProvider'
Register facades by adding these two lines in the aliases array:
'Form'=> 'Illuminate\Html\FormFacade',
'HTML'=> 'Illuminate\Html\HtmlFacade'
I encountered a lot of problems when using jaxb in Maven but i managed to solve your problem by doing the following
First create a schema.xjc file
<?xml version="1.0" encoding="UTF-8"?>
<jaxb:bindings xmlns:jaxb="http://java.sun.com/xml/ns/jaxb"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
jaxb:version="2.0">
<jaxb:bindings schemaLocation="YOUR_URL?wsdl#types?schema1">
<jaxb:schemaBindings>
<jaxb:package name="your.package.name.schema1"/>
</jaxb:schemaBindings>
</jaxb:bindings>
<jaxb:bindings schemaLocation="YOUR_URL??wsdl#types?schema2">
<jaxb:schemaBindings>
<jaxb:package name="your.package.name.schema2"/>
</jaxb:schemaBindings>
</jaxb:bindings>
</jaxb:bindings>
The package name can be anything you want it to be, as long as it doesn't contain any reserved keywords in Java
Next you have to create the wsimport.bat script to generate your packaged and code at the preferred location.
cd C:\YOUR\PATH\TO\PLACE\THE\PACKAGES
wsimport -keep -verbose -b "C:\YOUR\PATH\TO\schema.xjb" YOUR_URL?wsdl
pause
If you do not want to use cd, you can put the wsimport.bat in "C:\YOUR\PATH\TO\PLACE\THE\PACKAGES"
If you run it without -keep -verbose it will only generate the packages but not the .java files.
The -b will make sure the schema.xjc is used when generating
It took me a while, but here's how I made it dynamic. It doesn't depend on a sorted table.
First I started with a column of state names (Column A) and a column of aircraft in each state (Column B). (Row 1 is a header row).
Finding the cell that contains the number of aircraft was:
=MATCH(MAX($B$2:$B$54),$B$2:$B$54,0)+MIN(ROW($B$2:$B$54))-1
I put that into a cell and then gave that cell a name, "StateRow" Then using the tips from above, I wound up with this:
=INDIRECT(ADDRESS(StateRow,1))
This returns the name of the state from the dynamic value in row "StateRow", column 1
Now, as the values in the count column change over time as more data is entered, I always know which state has the most aircraft.
The best way is to prevent the default action. In the case of anchor tag, the default behavior is redirecting to href
specified address.
So following javascript works best in the situation:
$('#ThisLink').click(function(e)
{
e.preventDefault();
});
It can be useful for lazy-loading. Say the object in question is stored in a database, and you don't want to go get it unless you need it. If the object is retrieved by a getter, then the internal object can be null until somebody asks for it, then you can go get it on the first call to the getter.
I had a base page class in a project that was handed to me that was loading some data from a couple different web service calls, but the data in those web service calls wasn't always used in all child pages. Web services, for all of the benefits, pioneer new definitions of "slow", so you don't want to make a web service call if you don't have to.
I moved from public fields to getters, and now the getters check the cache, and if it's not there call the web service. So with a little wrapping, a lot of web service calls were prevented.
So the getter saves me from trying to figure out, on each child page, what I will need. If I need it, I call the getter, and it goes to find it for me if I don't already have it.
protected YourType _yourName = null;
public YourType YourName{
get
{
if (_yourName == null)
{
_yourName = new YourType();
return _yourName;
}
}
}
Would the following Macro help you?
Sub activateSheet(sheetname As String)
'activates sheet of specific name
Worksheets(sheetname).Activate
End Sub
Basically you want to make use of the .Activate function. Or you can use the .Select function like so:
Sub activateSheet(sheetname As String)
'selects sheet of specific name
Sheets(sheetname).Select
End Sub
INSERT INTO Table
( Event_ID
, col2
...
)
SELECT "155"
, col2
...
FROM Table WHERE Event_ID = "120"
Here, the col2, ... represent the remaining columns (the ones other than Event_ID) in your table.
While both reducebykey and groupbykey will produce the same answer, the reduceByKey example works much better on a large dataset. That's because Spark knows it can combine output with a common key on each partition before shuffling the data.
On the other hand, when calling groupByKey - all the key-value pairs are shuffled around. This is a lot of unnessary data to being transferred over the network.
for more detailed check this below link
I found the answer and I tried to translate it to english: This question still arised, even in technical interviews. In fact, there is a big resemblance between the two, but also there are some differences.
The constructor is part of ECMAScript. On the other hand ngOnInit() is a notion of angular.
We can call the constructors in all classes even if we do not use Angular
LifeCycle: The constructor is called before ngOnInt ()
In the constructor we can not call HTML elements. However, in ngOnInit () we can.
Generally, calls of services in the ngOnInit () and not in the constructor
wt = tt - cpu tm.
Tt = cpu tm + wt.
Where wt
is a waiting time and tt
is turnaround time. Cpu time is also called burst time.
Leeroy & Richard Parnaby-King:
UPDATE: As of spring 2018 this is no longer possible for cross-origin hrefs. So if you want to create on a domain other than imgur.com it will not work as intended. Chrome deprecations and removals announcement
function forceDownload(url, fileName){
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.responseType = "blob";
xhr.onload = function(){
var urlCreator = window.URL || window.webkitURL;
var imageUrl = urlCreator.createObjectURL(this.response);
var tag = document.createElement('a');
tag.href = imageUrl;
tag.download = fileName;
document.body.appendChild(tag);
tag.click();
document.body.removeChild(tag);
}
xhr.send();
}
declare @x INT = 1 /* Declares an integer variable named "x" with the value of 1 */
PRINT 'There are ' + CAST(@x AS VARCHAR) + ' alias combinations did not match a record' /* Prints a string concatenated with x casted as a varchar */
I have found a solution for the same question on this site
from tkinter import Tk
from tkinter.ttk import Label
root = Tk()
Label(root, text="Hello world").pack()
# Apparently a common hack to get the window size. Temporarily hide the
# window to avoid update_idletasks() drawing the window in the wrong
# position.
root.withdraw()
root.update_idletasks() # Update "requested size" from geometry manager
x = (root.winfo_screenwidth() - root.winfo_reqwidth()) / 2
y = (root.winfo_screenheight() - root.winfo_reqheight()) / 2
root.geometry("+%d+%d" % (x, y))
# This seems to draw the window frame immediately, so only call deiconify()
# after setting correct window position
root.deiconify()
root.mainloop()
sure, I changed it correspondingly to my purposes, it works.
Only such dialog is FileDialog. Its part of WinForms, but its actually only wrapper around WinAPI standard OS file dialog. And I don't think it is ugly, its actually part of OS, so it looks like OS it is run on.
Other way, there is nothing to help you with. You either need to look for 3rd party implementation, either free (and I don't think there are any good) or paid.
There are two related error messages that may tell you something is wrong with declarations and/or imports.
The first is the one you are referring to, which can be generated by NOT putting an #import in your .m (or .pch file) while declaring an @class in your .h.
The second you might see, if you had a method in your States class like:
- (void)logout:(NSTimer *)timer
after adding the #import is this:
No visible @interface for "States" declares the selector 'logout:'
If you see this, you need to check and see if you declared your "logout" method (in this instance) in the .h file of the class you're importing or forwarding.
So in your case, you would need a:
- (void)logout:(NSTimer *)timer;
in your States class's .h to make one or both of these related errors disappear.
Such error happens when,
1. You misspell module name which you injected.
2. If you missed to include js file of that module.
Sometimes people write js file name instead of the module name which we are injecting.
In these cases what happens is angular tries to look for the module provided in the square bracket []. If it doesn't find the module, it throws error.
Classic mode (the only mode in IIS6 and below) is a mode where IIS only works with ISAPI extensions and ISAPI filters directly. In fact, in this mode, ASP.NET is just an ISAPI extension (aspnet_isapi.dll) and an ISAPI filter (aspnet_filter.dll). IIS just treats ASP.NET as an external plugin implemented in ISAPI and works with it like a black box (and only when it's needs to give out the request to ASP.NET). In this mode, ASP.NET is not much different from PHP or other technologies for IIS.
Integrated mode, on the other hand, is a new mode in IIS7 where IIS pipeline is tightly integrated (i.e. is just the same) as ASP.NET request pipeline. ASP.NET can see every request it wants to and manipulate things along the way. ASP.NET is no longer treated as an external plugin. It's completely blended and integrated in IIS. In this mode, ASP.NET HttpModule
s basically have nearly as much power as an ISAPI filter would have had and ASP.NET HttpHandler
s can have nearly equivalent capability as an ISAPI extension could have. In this mode, ASP.NET is basically a part of IIS.
You would have to watch the DOM node changes. There is an API called MutationObserver
, but it looks like the support for it is very limited. This SO answer has a link to the status of the API, but it seems like there is no support for it in IE or Opera so far.
One way you could get around this problem is to have the part of the code that modifies the data-select-content-val
attribute dispatch an event that you can listen to.
For example, see: http://jsbin.com/arucuc/3/edit on how to tie it together.
The code here is
$(function() {
// Here you register for the event and do whatever you need to do.
$(document).on('data-attribute-changed', function() {
var data = $('#contains-data').data('mydata');
alert('Data changed to: ' + data);
});
$('#button').click(function() {
$('#contains-data').data('mydata', 'foo');
// Whenever you change the attribute you will user the .trigger
// method. The name of the event is arbitrary
$(document).trigger('data-attribute-changed');
});
$('#getbutton').click(function() {
var data = $('#contains-data').data('mydata');
alert('Data is: ' + data);
});
});
The standard way to add Multiple functions
<button (click)="removeAt(element.bookId); openDeleteDialog()"> Click Here</button>
or
<button (click)="removeAt(element.bookId)" (click)="openDeleteDialog()"> Click Here</button>
Save the following script as something like findPK.sql.
set verify off
accept TABLE_NAME char prompt 'Table name>'
SELECT cols.column_name
FROM all_constraints cons NATURAL JOIN all_cons_columns cols
WHERE cons.constraint_type = 'P' AND table_name = UPPER('&TABLE_NAME');
It can then be called using
@findPK
See here, this can help you:
public static boolean setObject(Context context, Object o) {
Field[] fields = o.getClass().getFields();
SharedPreferences sp = context.getSharedPreferences(o.getClass()
.getName(), Context.MODE_PRIVATE);
Editor editor = sp.edit();
for (int i = 0; i < fields.length; i++) {
Class<?> type = fields[i].getType();
if (isSingle(type)) {
try {
final String name = fields[i].getName();
if (type == Character.TYPE || type.equals(String.class)) {
Object value = fields[i].get(o);
if (null != value)
editor.putString(name, value.toString());
} else if (type.equals(int.class)
|| type.equals(Short.class))
editor.putInt(name, fields[i].getInt(o));
else if (type.equals(double.class))
editor.putFloat(name, (float) fields[i].getDouble(o));
else if (type.equals(float.class))
editor.putFloat(name, fields[i].getFloat(o));
else if (type.equals(long.class))
editor.putLong(name, fields[i].getLong(o));
else if (type.equals(Boolean.class))
editor.putBoolean(name, fields[i].getBoolean(o));
} catch (IllegalAccessException e) {
LogUtils.e(TAG, e);
} catch (IllegalArgumentException e) {
LogUtils.e(TAG, e);
}
} else {
// FIXME ???????
}
}
return editor.commit();
}
May I expand on the question and ask if Git work well on MacOS?
Reply to Comments: Thanks for the news, I'd been looking forward to trying it out. I'll install it at home on my Mac.
Assume that you have an array of classes to being added, you can use ES6 spread syntax:
let classes = ['first', 'second', 'third'];
elem.classList.add(...classes);
I've always used this:
WHERE myDate BETWEEN startDate AND (endDate+1)
In bash script I do this to check if image exists by tag :
IMAGE_NAME="mysql:5.6"
if docker image ls -a "$IMAGE_NAME" | grep -Fq "$IMAGE_NAME" 1>/dev/null; then
echo "could found image $IMAGE_NAME..."
fi
Example script above checks if mysql image with 5.6 tag exists. If you want just check if any mysql image exists without specific version then just pass repository name without tag as this :
IMAGE_NAME="mysql"
Swift 3.0
Simplest solution which will give you indexPath for visible cells..
yourCollectionView.indexPathsForVisibleItems
will return the array of indexpath.
Just take the first object from array like this.
yourCollectionView.indexPathsForVisibleItems.first
I guess it should work fine with Objective - C as well.
You are trying to load a XIB named DetailViewController
, but no such XIB exists or it's not member of your current target.
filter expects to get a function and something that it can iterate over. The function should return True or False for each element in the iterable. In your particular example, what you're looking to do is something like the following:
In [47]: def greetings(x):
....: return x == "hello"
....:
In [48]: filter(greetings, ["hello", "goodbye"])
Out[48]: ['hello']
Note that in Python 3, it may be necessary to use list(filter(greetings, ["hello", "goodbye"]))
to get this same result.
I would like to add another point of view in order to solve this problem, specially if you have a small number of columns to remove.
You could use a DB tool like MySQL Workbench in order to generate the select statement for you, so you just have to manually remove those columns for the generated statement and copy it to your SQL script.
In MySQL Workbench the way to generate it is:
Right click on the table -> send to Sql Editor -> Select All Statement.
Give the div you don't want him inheriting the property background too.
Use a list comprehension:
[item for item in x if item not in y]
If you want to use the -
infix syntax, you can just do:
class MyList(list):
def __init__(self, *args):
super(MyList, self).__init__(args)
def __sub__(self, other):
return self.__class__(*[item for item in self if item not in other])
you can then use it like:
x = MyList(1, 2, 3, 4)
y = MyList(2, 5, 2)
z = x - y
But if you don't absolutely need list properties (for example, ordering), just use sets as the other answers recommend.
in php.ini file,uncomment this one
sendmail_path = "\"C:\xampp\sendmail\sendmail.exe\" -t"
;sendmail_path="C:\xampp\mailtodisk\mailtodisk.exe"
and in sendmail.ini
smtp_server=smtp.gmail.com
smtp_port=465
error_logfile=error.log
debug_logfile=debug.log
[email protected]
auth_password=yourpassword
[email protected]
hostname=localhost
configure this one..it will works...it working fine for me.
thanks.
For a single style attribute, you can use the following syntax:
<div [style.background-color]="style1 ? 'red' : (style2 ? 'blue' : null)">
I assumed that the background color should not be set if neither style1
nor style2
is true
.
Since the question title mentions ngStyle
, here is the equivalent syntax with that directive:
<div [ngStyle]="{'background-color': style1 ? 'red' : (style2 ? 'blue' : null) }">
After hours of struggling, I solved it by including the following within app/build.gradle:
android {
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
This has been answered in a separate question and resolved the problem for me. Be sure to vote up the original person's answer.
ASP.Net error: "The type 'foo' exists in both "temp1.dll" and "temp2.dll"
Add the batch="false" attribute to the "compilation" element of the web.config file.
This problem occurs because of the way in which ASP.NET 2.0 uses the application references and the folder structure of the application to compile the application. If the batch property of the element in the web.config file for the application is set to true, ASP.NET 2.0 compiles each folder in the application into a separate assembly.
http://www.sellsbrothers.com/news/showTopic.aspx?ixTopic=1995
If your input was structured as XML, you could use the importXML
function. (More info here at quirksmode).
If it isn't XML, and there isn't an equivalent function for importing plain text, then you could open it in a hidden iframe and then read the contents from there.
I came here with the same requirements but @lvc and @Preet's answers seems more inline with what column -t
produces in that columns have different widths:
>>> rows = [ ['a', 'b', 'c', 'd']
... , ['aaaaaaaaaa', 'b', 'c', 'd']
... , ['a', 'bbbbbbbbbb', 'c', 'd']
... ]
...
>>> widths = [max(map(len, col)) for col in zip(*rows)]
>>> for row in rows:
... print " ".join((val.ljust(width) for val, width in zip(row, widths)))
...
a b c d
aaaaaaaaaa b c d
a bbbbbbbbbb c d
StarUML does just that and it is free. Unfortunately it hasn't been updated for a while. There were a couple of offshoot projects (as the project admins wouldn't allow it to be taken over) but they too have died a death.
Try to use the latest com.fasterxml.jackson.core/jackson-databind
.
I upgraded it to 2.9.4
and it works now.
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.4</version>
</dependency>
dotnet
now includes a command for gitignore
.
Open cmd.exe
from your project folder and type:
dotnet new gitignore
This will add a path to your Python process / instance (i.e. the running executable). The path will not be modified for any other Python processes. Another running Python program will not have its path modified, and if you exit your program and run again the path will not include what you added before. What are you are doing is generally correct.
set.py:
import sys
sys.path.append("/tmp/TEST")
loop.py
import sys
import time
while True:
print sys.path
time.sleep(1)
run: python loop.py &
This will run loop.py, connected to your STDOUT, and it will continue to run in the background. You can then run python set.py
. Each has a different set of environment variables. Observe that the output from loop.py
does not change because set.py
does not change loop.py
's environment.
A note on importing
Python imports are dynamic, like the rest of the language. There is no static linking going on. The import is an executable line, just like sys.path.append...
.
You have a few options:
1) Use the Bundle from the Intent:
Intent mIntent = new Intent(this, Example.class);
Bundle extras = mIntent.getExtras();
extras.putString(key, value);
2) Create a new Bundle
Intent mIntent = new Intent(this, Example.class);
Bundle mBundle = new Bundle();
mBundle.putString(key, value);
mIntent.putExtras(mBundle);
3) Use the putExtra() shortcut method of the Intent
Intent mIntent = new Intent(this, Example.class);
mIntent.putExtra(key, value);
Then, in the launched Activity, you would read them via:
String value = getIntent().getExtras().getString(key)
NOTE: Bundles have "get" and "put" methods for all the primitive types, Parcelables, and Serializables. I just used Strings for demonstrational purposes.
You need either of the following depending on the type of the container of T
elements you pass to the builder (Collection<T>
or T[]
):
Collection<T> YOUR_COLLECTION
:Collections.unmodifiableList(new ArrayList<>(YOUR_COLLECTION));
T[] YOUR_ARRAY
:Arrays.asList(YOUR_ARRAY);
Simple as that
When a Javascript object property's name doesn't begin with either an underscore or a letter, you cant use the dot notation (like Game.status[0].0
), and you must use the alternative notation, which is Game.status[0][0]
.
One different note, do you really need it to be an object inside the status array? If you're using the object like an array, why not use a real array instead?
I like @huynhjl's answer, it led me down the right path. However, it isn't great at handling error conditions. If the desired node does not exist, you get a cast exception. I've adapted this slightly to make use of Option
to better handle this.
class CC[T] {
def unapply(a:Option[Any]):Option[T] = if (a.isEmpty) {
None
} else {
Some(a.get.asInstanceOf[T])
}
}
object M extends CC[Map[String, Any]]
object L extends CC[List[Any]]
object S extends CC[String]
object D extends CC[Double]
object B extends CC[Boolean]
for {
M(map) <- List(JSON.parseFull(jsonString))
L(languages) = map.get("languages")
language <- languages
M(lang) = Some(language)
S(name) = lang.get("name")
B(active) = lang.get("is_active")
D(completeness) = lang.get("completeness")
} yield {
(name, active, completeness)
}
Of course, this doesn't handle errors so much as avoid them. This will yield an empty list if any of the json nodes are missing. You can use a match
to check for the presence of a node before acting...
for {
M(map) <- Some(JSON.parseFull(jsonString))
} yield {
map.get("languages") match {
case L(languages) => {
for {
language <- languages
M(lang) = Some(language)
S(name) = lang.get("name")
B(active) = lang.get("is_active")
D(completeness) = lang.get("completeness")
} yield {
(name, active, completeness)
}
}
case None => "bad json"
}
}
"SQL Server Reporting Service" was causing issues in my system, after stopping it, Apache started working fine
Swift 3 version of Confile's answer:
import UIKit
extension UIView {
func addTopBorderWithColor(color: UIColor, width: CGFloat) {
let border = CALayer()
border.backgroundColor = color.cgColor
border.frame = CGRect(x: 0, y: 0, width: self.frame.size.width, height: width)
self.layer.addSublayer(border)
}
func addRightBorderWithColor(color: UIColor, width: CGFloat) {
let border = CALayer()
border.backgroundColor = color.cgColor
border.frame = CGRect(x: self.frame.size.width - width, y: 0, width: width, height: self.frame.size.height)
self.layer.addSublayer(border)
}
func addBottomBorderWithColor(color: UIColor, width: CGFloat) {
let border = CALayer()
border.backgroundColor = color.cgColor
border.frame = CGRect(x: 0, y: self.frame.size.height - width, width: self.frame.size.width, height: width)
self.layer.addSublayer(border)
}
func addLeftBorderWithColor(color: UIColor, width: CGFloat) {
let border = CALayer()
border.backgroundColor = color.cgColor
border.frame = CGRect(x: 0, y: 0, width: width, height: self.frame.size.height)
self.layer.addSublayer(border)
}
}
Usage when using auto layout:
class CustomView: UIView {
override func awakeFromNib() {
super.awakeFromNib()
}
override func layoutSubviews() {
addBottomBorderWithColor(color: UIColor.white, width: 1)
}
}
It's a bad idea to count the td
elements to get the number of columns in your table, because td
elements can span multiple columns with colspan
.
Here's a simple solution using jquery:
var length = 0;_x000D_
$("tr:first").find("td,th").each(function(){_x000D_
var colspan = $(this).attr("colspan");_x000D_
if(typeof colspan !== "undefined" && colspan > 0){_x000D_
length += parseInt(colspan);_x000D_
}else{_x000D_
length += 1;_x000D_
}_x000D_
});_x000D_
_x000D_
$("div").html("number of columns: "+length);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<table>_x000D_
<tr>_x000D_
<td>single</td>_x000D_
<td colspan="2">double</td>_x000D_
<td>single</td>_x000D_
<td>single</td>_x000D_
</tr>_x000D_
</table>_x000D_
<div></div>
_x000D_
For a plain Javascript solution, see Emilio's answer.
Modify your project.json or *.csproj file. Add a dependency entry with the name of the package and the version desired.
JSON example:
{
"dependencies" : {
"AutoMapper": "5.2.0"
}
}
I had similar problem, then I tried writing this from JavaScript and it works! : referenceToYourInputFile.value = "" ;
One way to do this is just to test against the return value. Because you're getting <_sre.SRE_Match object at ...>
it means that this will evaluate to true. When the regular expression isn't matched you'll the return value None, which evaluates to false.
import re
if re.search("c", "abcdef"):
print "hi"
Produces hi
as output.
with open("test.txt", "a") as myfile:
myfile.write("appended text")
The Java Virtual Machine takes two command line arguments which set the initial and maximum heap sizes: -Xms and -Xmx. You can add a system environment variable named _JAVA_OPTIONS, and set the heap size values there.
For example if you want a 512Mb initial and 1024Mb maximum heap size you could use:
under Windows:
SET _JAVA_OPTIONS = -Xms512m -Xmx1024m
under Linux:
export _JAVA_OPTIONS="-Xms512m -Xmx1024m"
It is possible to read the default JVM heap size programmatically by using totalMemory() method of Runtime class. Use following code to read JVM heap size.
public class GetHeapSize {
public static void main(String[]args){
//Get the jvm heap size.
long heapSize = Runtime.getRuntime().totalMemory();
//Print the jvm heap size.
System.out.println("Heap Size = " + heapSize);
}
}
You need astype
:
df['zipcode'] = df.zipcode.astype(str)
#df.zipcode = df.zipcode.astype(str)
For converting to categorical
:
df['zipcode'] = df.zipcode.astype('category')
#df.zipcode = df.zipcode.astype('category')
Another solution is Categorical
:
df['zipcode'] = pd.Categorical(df.zipcode)
Sample with data:
import pandas as pd
df = pd.DataFrame({'zipcode': {17384: 98125, 2680: 98107, 722: 98005, 18754: 98109, 14554: 98155}, 'bathrooms': {17384: 1.5, 2680: 0.75, 722: 3.25, 18754: 1.0, 14554: 2.5}, 'sqft_lot': {17384: 1650, 2680: 3700, 722: 51836, 18754: 2640, 14554: 9603}, 'bedrooms': {17384: 2, 2680: 2, 722: 4, 18754: 2, 14554: 4}, 'sqft_living': {17384: 1430, 2680: 1440, 722: 4670, 18754: 1130, 14554: 3180}, 'floors': {17384: 3.0, 2680: 1.0, 722: 2.0, 18754: 1.0, 14554: 2.0}})
print (df)
bathrooms bedrooms floors sqft_living sqft_lot zipcode
722 3.25 4 2.0 4670 51836 98005
2680 0.75 2 1.0 1440 3700 98107
14554 2.50 4 2.0 3180 9603 98155
17384 1.50 2 3.0 1430 1650 98125
18754 1.00 2 1.0 1130 2640 98109
print (df.dtypes)
bathrooms float64
bedrooms int64
floors float64
sqft_living int64
sqft_lot int64
zipcode int64
dtype: object
df['zipcode'] = df.zipcode.astype('category')
print (df)
bathrooms bedrooms floors sqft_living sqft_lot zipcode
722 3.25 4 2.0 4670 51836 98005
2680 0.75 2 1.0 1440 3700 98107
14554 2.50 4 2.0 3180 9603 98155
17384 1.50 2 3.0 1430 1650 98125
18754 1.00 2 1.0 1130 2640 98109
print (df.dtypes)
bathrooms float64
bedrooms int64
floors float64
sqft_living int64
sqft_lot int64
zipcode category
dtype: object
I had this problem also. I set the correct settings and have enabled less secure apps but it still did not work. Finally, I enabled this https://accounts.google.com/UnlockCaptcha, and it worked for me. I hope this helps someone.
.element{position: relative;top: 50%;transform: translateY(-50%);}
Add this small code in the CSS property of your element. It is awesome. Try it!
If you're new to Subversion you may want to check out this post on SmashingMagazine.com, appropriately titled Ultimate Round-Up for Version Control with SubVersion.
It covers getting started with SubVersion with links to tutorials, reference materials, & book suggestions.
It covers tools (many are compatible windows), and it mentions AnkhSVN as a Visual Studio compatible plugin. The comments also mention VisualSVN as an alternative.
I had the same issue. Thanks for the answers above, I solved my issue. If there are people facing the same problem, here is two way to solve it:
{!! $news->body !!}
<?php echo $string ?>
I hope it helps.
This is how Apple does it for classes like NSString:
In the header file:
enum {
PlayerStateOff,
PlayerStatePlaying,
PlayerStatePaused
};
typedef NSInteger PlayerState;
Refer to Coding Guidelines at http://developer.apple.com/
a=['pear', 'apple', 'orange', 'apple'];
b={};
max='', maxi=0;
for(let k of a) {
if(b[k]) b[k]++; else b[k]=1;
if(maxi < b[k]) { max=k; maxi=b[k] }
}
$("a[href*='id=ABC']").addClass('active_jquery_menu');
To find the point where to add the -lm in Eclipse-IDE is really horrible, so it took me some time.
If someone else also uses Edlipse, here's the way how to add the command:
Project -> Properties -> C/C++ Build -> Settings -> GCC C Linker -> Miscelleaneous -> Linker flags: in this field add the command -lm
index.html
<!DOCTYPE html>
<html>
<body>
<form action="submit.php" method="POST">
First name: <input type="text" name="firstname" /><br /><br />
Last name: <input type="text" name="lastname" /><br />
<input type="submit" value="Submit" />
</form>
</body>
</html>
After that one more file which page you want to display after pressing the submit button
submit.php
<html>
<body>
Your First Name is - <?php echo $_POST["firstname"]; ?><br>
Your Last Name is - <?php echo $_POST["lastname"]; ?>
</body>
</html>
For already created files:
find . \( -type f -exec chmod g=r,o=r {} \; \) , \( -type d -exec chmod g=rx,o=rx {} \; \)
For future created files:
sudo nano /etc/profile
And set:
umask 022
Common modes are:
you can delete the objects directly from the admin panel or else there is also an option to delete specific or selected id from an interactive shell by typing in python3 manage.py shell (python3 in Linux). If you want the user to delete the objects through the browser (with provided visual interface) e.g. of an employee whose ID is 6 from the database, we can achieve this with the following code, emp = employee.objects.get(id=6).delete()
THIS WILL DELETE THE EMPLOYEE WITH THE ID is 6.
If you wish to delete the all of the employees exist in the DB instead of get(), specify all() as follows: employee.objects.all().delete()
getView()
method create new View
or ViewGroup
for each row of Listview
or Spinner . You can define this View
or ViewGroup
in a Layout XML
file in res/layout
folder and can give the reference it to Adapter
class Object.
if you have 4 item in a Array passed to Adapter. getView()
method will create 4 View for 4 rows of Adaper.
LayoutInflater class has a Method inflate() whic create View Object from XML resource layout.
Had the same problem on another server, but realized that locales are messed.
export LC_ALL="en_US.UTF-8"
fixed the problem
The three things that get installed that you will need to delete are:
Now on my linux system these live in:
But on a windows system they are more likely to be entirely within the Python distribution directory. I have no idea about OSX except it is more likey to follow the linux pattern.
There is a default text editor that will be used when Git needs you to type in a message. By default, Git uses your system’s default editor, which is generally Vi or Vim. In your case, it is Vim that Git has chosen. See How do I make Git use the editor of my choice for commits? for details of how to choose another editor. Meanwhile...
You'll want to enter a message before you leave Vim:
...will start a new line for you to type in.
To exit (g)Vim type:
It's worth getting to know Vim, as you can use it for editing text on almost any platform. I recommend the Vim Tutor
, I used it many years ago and have never looked back (barely a day goes by when I don't use Vim).
You can use stristr()
or strpos()
. Both return false if nothing is found.
declare this
var intro;
outside of $(document).ready()
because, $(document).ready()
will hide your variable from global scope.
Code
var intro;
$(document).ready(function() {
if ($('.intro_check').is(':checked')) {
intro = true;
$('.intro').wrap('<div class="disabled"></div>');
};
$('.intro_check').change(function(){
if(this.checked) {
intro = false;
$('.enabled').removeClass('enabled').addClass('disabled');
} else {
intro = true;
if($('.intro').exists()) {
$('.disabled').removeClass('disabled').addClass('enabled');
} else {
$('.intro').wrap('<div class="disabled"></div>');
}
}
});
});
Another way:
window.intro = undefined;
$(document).ready(function() {
if ($('.intro_check').is(':checked')) {
window.intro = true;
$('.intro').wrap('<div class="disabled"></div>');
};
$('.intro_check').change(function(){
if(this.checked) {
window.intro = false;
$('.enabled').removeClass('enabled').addClass('disabled');
} else {
window.intro = true;
if($('.intro').exists()) {
$('.disabled').removeClass('disabled').addClass('enabled');
} else {
$('.intro').wrap('<div class="disabled"></div>');
}
}
});
});
console.log(intro);
outside of DOM ready function (currently you've) will log undefined
, but within DOM ready it will give you true/ false.
console.log
execute before DOM ready execute, because DOM ready execute after all resource appeared to DOM i.e after DOM is prepared, so I think you'll always get absurd result.I need to use it outside of DOM ready function
You can use following approach:
var intro = undefined;
$(document).ready(function() {
if ($('.intro_check').is(':checked')) {
intro = true;
introCheck();
$('.intro').wrap('<div class="disabled"></div>');
};
$('.intro_check').change(function() {
if (this.checked) {
intro = true;
} else {
intro = false;
}
introCheck();
});
});
function introCheck() {
console.log(intro);
}
After change the value of intro
I called a function that will fire with new value of intro
.
One possible thing you could do is use the Dictionary object straight out of the box and then just extend it with your own modifications:
public class TokenTree : Dictionary<string, string>
{
public IDictionary<string, string> SubPairs;
}
This gives you the advantage of not having to enforce the rules of IDictionary for your Key (e.g., key uniqueness, etc).
And yup you got the concept of the constructor right :)
Python has importing and namespacing, which are good. In Python you can import into the current namespace, like:
>>> from test import disp
>>> disp('World!')
Or with a namespace:
>>> import test
>>> test.disp('World!')
You can also get access to C#/.NET methods, and the following also works:
$string1 = "Slim Shady, "
$string2 = "The real slim shady"
$concatString = [System.String]::Concat($string1, $string2)
Output:
Slim Shady, The real slim shady
let's assume this hierarchy:
class Creature{}// X
class Animal extends Creature{}// Y
class Fish extends Animal{}// Z
class Shark extends Fish{}// A
class HammerSkark extends Shark{}// B
class DeadHammerShark extends HammerSkark{}// C
Let's clarify PE - Producer Extends:
List<? extends Shark> sharks = new ArrayList<>();
Why you cannot add objects that extend "Shark" in this list? like:
sharks.add(new HammerShark());//will result in compilation error
Since you have a list that can be of type A, B or C at runtime, you cannot add any object of type A, B or C in it because you can end up with a combination that is not allowed in java.
In practice, the compiler can indeed see at compiletime that you add a B:
sharks.add(new HammerShark());
...but it has no way to tell if at runtime, your B will be a subtype or supertype of the list type. At runtime the list type can be any of the types A, B, C. So you cannot end up adding HammerSkark (super type) in a list of DeadHammerShark for example.
*You will say: "OK, but why can't I add HammerSkark in it since it is the smallest type?". Answer: It is the smallest you know. But HammerSkark can be extended too by somebody else and you end up in the same scenario.
Let's clarify CS - Consumer Super:
In the same hierarchy we can try this:
List<? super Shark> sharks = new ArrayList<>();
What and why you can add to this list?
sharks.add(new Shark());
sharks.add(new DeadHammerShark());
sharks.add(new HammerSkark());
You can add the above types of objects because anything below shark(A,B,C) will always be subtypes of anything above shark (X,Y,Z). Easy to understand.
You cannot add types above Shark, because at runtime the type of added object can be higher in hierarchy than the declared type of the list(X,Y,Z). This is not allowed.
But why you cannot read from this list? (I mean you can get an element out of it, but you cannot assign it to anything other than Object o):
Object o;
o = sharks.get(2);// only assignment that works
Animal s;
s = sharks.get(2);//doen't work
At runtime, the type of list can be any type above A: X, Y, Z, ... The compiler can compile your assignment statement (which seems correct) but, at runtime the type of s (Animal) can be lower in hierarchy than the declared type of the list(which could be Creature, or higher). This is not allowed.
To sum up
We use <? super T>
to add objects of types equal or below T
to the List
. We cannot read from
it.
We use <? extends T>
to read objects of types equal or below T
from list. We cannot add element to it.
This is all generally covered by Section 23.3.2 of SystemVerilog IEEE Std 1800-2012.
The simplest way is to instantiate in the main section of top, creating a named instance and wiring the ports up in order:
module top(
input clk,
input rst_n,
input enable,
input [9:0] data_rx_1,
input [9:0] data_rx_2,
output [9:0] data_tx_2
);
subcomponent subcomponent_instance_name (
clk, rst_n, data_rx_1, data_tx );
endmodule
This is described in Section 23.3.2.1 of SystemVerilog IEEE Std 1800-2012.
This has a few draw backs especially regarding the port order of the subcomponent code. simple refactoring here can break connectivity or change behaviour. for example if some one else fixs a bug and reorders the ports for some reason, switching the clk and reset order. There will be no connectivity issue from your compiler but will not work as intended.
module subcomponent(
input rst_n,
input clk,
...
It is therefore recommended to connect using named ports, this also helps tracing connectivity of wires in the code.
module top(
input clk,
input rst_n,
input enable,
input [9:0] data_rx_1,
input [9:0] data_rx_2,
output [9:0] data_tx_2
);
subcomponent subcomponent_instance_name (
.clk(clk), .rst_n(rst_n), .data_rx(data_rx_1), .data_tx(data_tx) );
endmodule
This is described in Section 23.3.2.2 of SystemVerilog IEEE Std 1800-2012.
Giving each port its own line and indenting correctly adds to the readability and code quality.
subcomponent subcomponent_instance_name (
.clk ( clk ), // input
.rst_n ( rst_n ), // input
.data_rx ( data_rx_1 ), // input [9:0]
.data_tx ( data_tx ) // output [9:0]
);
So far all the connections that have been made have reused inputs and output to the sub module and no connectivity wires have been created. What happens if we are to take outputs from one component to another:
clk_gen(
.clk ( clk_sub ), // output
.en ( enable ) // input
subcomponent subcomponent_instance_name (
.clk ( clk_sub ), // input
.rst_n ( rst_n ), // input
.data_rx ( data_rx_1 ), // input [9:0]
.data_tx ( data_tx ) // output [9:0]
);
This nominally works as a wire for clk_sub is automatically created, there is a danger to relying on this. it will only ever create a 1 bit wire by default. An example where this is a problem would be for the data:
Note that the instance name for the second component has been changed
subcomponent subcomponent_instance_name (
.clk ( clk_sub ), // input
.rst_n ( rst_n ), // input
.data_rx ( data_rx_1 ), // input [9:0]
.data_tx ( data_temp ) // output [9:0]
);
subcomponent subcomponent_instance_name2 (
.clk ( clk_sub ), // input
.rst_n ( rst_n ), // input
.data_rx ( data_temp ), // input [9:0]
.data_tx ( data_tx ) // output [9:0]
);
The issue with the above code is that data_temp is only 1 bit wide, there would be a compile warning about port width mismatch. The connectivity wire needs to be created and a width specified. I would recommend that all connectivity wires be explicitly written out.
wire [9:0] data_temp
subcomponent subcomponent_instance_name (
.clk ( clk_sub ), // input
.rst_n ( rst_n ), // input
.data_rx ( data_rx_1 ), // input [9:0]
.data_tx ( data_temp ) // output [9:0]
);
subcomponent subcomponent_instance_name2 (
.clk ( clk_sub ), // input
.rst_n ( rst_n ), // input
.data_rx ( data_temp ), // input [9:0]
.data_tx ( data_tx ) // output [9:0]
);
Moving to SystemVerilog there are a few tricks available that save typing a handful of characters. I believe that they hinder the code readability and can make it harder to find bugs.
Use .port
with no brackets to connect to a wire/reg of the same name. This can look neat especially with lots of clk and resets but at some levels you may generate different clocks or resets or you actually do not want to connect to the signal of the same name but a modified one and this can lead to wiring bugs that are not obvious to the eye.
module top(
input clk,
input rst_n,
input enable,
input [9:0] data_rx_1,
input [9:0] data_rx_2,
output [9:0] data_tx_2
);
subcomponent subcomponent_instance_name (
.clk, // input **Auto connect**
.rst_n, // input **Auto connect**
.data_rx ( data_rx_1 ), // input [9:0]
.data_tx ( data_tx ) // output [9:0]
);
endmodule
This is described in Section 23.3.2.3 of SystemVerilog IEEE Std 1800-2012.
Another trick that I think is even worse than the one above is .*
which connects unmentioned ports to signals of the same wire. I consider this to be quite dangerous in production code. It is not obvious when new ports have been added and are missing or that they might accidentally get connected if the new port name had a counter part in the instancing level, they get auto connected and no warning would be generated.
subcomponent subcomponent_instance_name (
.*, // **Auto connect**
.data_rx ( data_rx_1 ), // input [9:0]
.data_tx ( data_tx ) // output [9:0]
);
This is described in Section 23.3.2.4 of SystemVerilog IEEE Std 1800-2012.
For updating a record:
UPDATE Employees SET [Photo] = (SELECT
MyImage.* from Openrowset(Bulk
'C:\photo.bmp', Single_Blob) MyImage)
where Id = 10
Notes:
jQuery.fn.extend
({
removeCss: function(cssName) {
return this.each(function() {
var curDom = $(this);
jQuery.grep(cssName.split(","),
function(cssToBeRemoved) {
curDom.css(cssToBeRemoved, '');
});
return curDom;
});
}
});
/*example code: I prefer JQuery extend so I can use it anywhere I want to use.
$('#searchJqueryObject').removeCss('background-color');
$('#searchJqueryObject').removeCss('background-color,height,width'); //supports comma separated css names.
*/
OR
//this parse style & remove style & rebuild style. I like the first one.. but anyway exploring..
jQuery.fn.extend
({
removeCSS: function(cssName) {
return this.each(function() {
return $(this).attr('style',
jQuery.grep($(this).attr('style').split(";"),
function(curCssName) {
if (curCssName.toUpperCase().indexOf(cssName.toUpperCase() + ':') <= 0)
return curCssName;
}).join(";"));
});
}
});
var voyageId = new Array();
$("input[name='voyageId[]']:checked:enabled").each(function () {
voyageId.push($(this).val());
});
Here's a zsh-only function that I like for its compactness. It uses the ‘A’ expansion modifier — see zshexpn(1).
realpath() { for f in "$@"; do echo ${f}(:A); done }
View view =(View) getActivity().findViewById(controlId);
Spinner spinner = (Spinner)view.findViewById(R.id.spinner1);
String valToSet = spinner.getSelectedItem().toString();
Instead of using fake dates like 0000-00-00 00:00:00
or 0001-01-01 00:00:00
(the latter should be accepted as it is a valid date), change your database schema, to allow NULL
values.
ALTER TABLE table_name MODIFY COLUMN date TIMESTAMP NULL
Here is the answer of my question. I've asked that again with some remarks. How to add support libraries?
The purpose of a view is to use the query over and over again. To that end, SQL Server, Oracle, etc. will typically provide a "cached" or "compiled" version of your view, thus improving its performance. In general, this should perform better than a "simple" query, though if the query is truly very simple, the benefits may be negligible.
Now, if you're doing a complex query, create the view.
The legend is part of the default options of the ChartJs library. So you do not need to explicitly add it as an option.
The library generates the HTML. It is merely a matter of adding that to the your page. For example, add it to the innerHTML of a given DIV. (Edit the default options if you are editing the colors, etc)
<div>
<canvas id="chartDiv" height="400" width="600"></canvas>
<div id="legendDiv"></div>
</div>
<script>
var data = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [
{
label: "The Flash's Speed",
fillColor: "rgba(220,220,220,0.2)",
strokeColor: "rgba(220,220,220,1)",
pointColor: "rgba(220,220,220,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(220,220,220,1)",
data: [65, 59, 80, 81, 56, 55, 40]
},
{
label: "Superman's Speed",
fillColor: "rgba(151,187,205,0.2)",
strokeColor: "rgba(151,187,205,1)",
pointColor: "rgba(151,187,205,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(151,187,205,1)",
data: [28, 48, 40, 19, 86, 27, 90]
}
]
};
var myLineChart = new Chart(document.getElementById("chartDiv").getContext("2d")).Line(data);
document.getElementById("legendDiv").innerHTML = myLineChart.generateLegend();
</script>
As of 2020 and Go version 1.13+, in Windows the best way for updating GOPATH is just typing in command prompt:
setx GOPATH C:\mynewgopath
CSVReader reader = new CSVReader(new FileReader(
"myfile.csv"));
try {
List<String[]> myEntries = reader.readAll();
for (String[] s : myEntries) {
for(String ss : s) {
System.out.print(", " + ss);
}
}
} catch (IOException e) {
e.printStackTrace();
}
I found that when I used the this callback function to ignore SSL certificates [System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}
I always got the error message Invoke-WebRequest : The underlying connection was closed: An unexpected error occurred on a send.
which sounds like the results you are having.
I found this forum post which lead me to the function below. I run this once inside the scope of my other code and it works for me.
function Ignore-SSLCertificates
{
$Provider = New-Object Microsoft.CSharp.CSharpCodeProvider
$Compiler = $Provider.CreateCompiler()
$Params = New-Object System.CodeDom.Compiler.CompilerParameters
$Params.GenerateExecutable = $false
$Params.GenerateInMemory = $true
$Params.IncludeDebugInformation = $false
$Params.ReferencedAssemblies.Add("System.DLL") > $null
$TASource=@'
namespace Local.ToolkitExtensions.Net.CertificatePolicy
{
public class TrustAll : System.Net.ICertificatePolicy
{
public bool CheckValidationResult(System.Net.ServicePoint sp,System.Security.Cryptography.X509Certificates.X509Certificate cert, System.Net.WebRequest req, int problem)
{
return true;
}
}
}
'@
$TAResults=$Provider.CompileAssemblyFromSource($Params,$TASource)
$TAAssembly=$TAResults.CompiledAssembly
## We create an instance of TrustAll and attach it to the ServicePointManager
$TrustAll = $TAAssembly.CreateInstance("Local.ToolkitExtensions.Net.CertificatePolicy.TrustAll")
[System.Net.ServicePointManager]::CertificatePolicy = $TrustAll
}
You need a development provisioning profile on your build machine. Apps can run on the simulator without a profile, but they are required to run on an actual device.
If you open the project in Xcode, it may automatically set up provisioning for you. Otherwise you will have to create go to the iOS Dev Center and create a profile.
git reset c14809fafb08b9e96ff2879999ba8c807d10fb07
is what you're after...
If you are fine with truncating the table of the model in question, you can specify a one-off default value of None
in the prompt. The migration will have superfluous default=None
while your code has no default. It can be applied just fine because there's no data in the table anymore which would require a default.
If you know what context managers are then you need nothing more to understand __enter__
and __exit__
magic methods. Lets see a very simple example.
In this example I am opening myfile.txt with help of open function. The try/finally block ensures that even if an unexpected exception occurs myfile.txt will be closed.
fp=open(r"C:\Users\SharpEl\Desktop\myfile.txt")
try:
for line in fp:
print(line)
finally:
fp.close()
Now I am opening same file with with statement:
with open(r"C:\Users\SharpEl\Desktop\myfile.txt") as fp:
for line in fp:
print(line)
If you look at the code, I didn't close the file & there is no try/finally block. Because with statement automatically closes myfile.txt . You can even check it by calling print(fp.closed)
attribute -- which returns True
.
This is because the file objects (fp in my example) returned by open function has two built-in methods __enter__
and __exit__
. It is also known as context manager. __enter__
method is called at the start of with block and __exit__
method is called at the end. Note: with statement only works with objects that support the context mamangement protocol i.e. they have __enter__
and __exit__
methods. A class which implement both methods is known as context manager class.
Now lets define our own context manager class.
class Log:
def __init__(self,filename):
self.filename=filename
self.fp=None
def logging(self,text):
self.fp.write(text+'\n')
def __enter__(self):
print("__enter__")
self.fp=open(self.filename,"a+")
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print("__exit__")
self.fp.close()
with Log(r"C:\Users\SharpEl\Desktop\myfile.txt") as logfile:
print("Main")
logfile.logging("Test1")
logfile.logging("Test2")
I hope now you have basic understanding of both __enter__
and __exit__
magic methods.
@robertc has it right, but you also need to notice that svg, #container
causes the svg to be scaled exponentially for anything but 100% (once for #container
and once for svg
).
In other words, if I applied 50% h/w to both elements, it's actually 50% of 50%, or .5 * .5, which equals .25, or 25% scale.
One selector works fine when used as @robertc suggests.
svg {
width:50%;
height:50%;
}
If you switch to the jQuery UI Dialog box, you can initialize the buttons array with the appropriate names like:
$("#id").dialog({
buttons: {
"Yes": function() {},
"No": function() {}
}
});
The most basic draggable code would be :
Element.prototype.drag = function(){
var mousemove = function(e){ // document mousemove
this.style.left = ( e.clientX - this.dragStartX ) + 'px';
this.style.top = ( e.clientY - this.dragStartY ) + 'px';
}.bind(this);
var mouseup = function(e){ // document mouseup
document.removeEventListener('mousemove',mousemove);
document.removeEventListener('mouseup',mouseup);
}.bind(this);
this.addEventListener('mousedown',function(e){ // element mousedown
this.dragStartX = e.offsetX;
this.dragStartY = e.offsetY;
document.addEventListener('mousemove',mousemove);
document.addEventListener('mouseup',mouseup);
}.bind(this));
this.style.position = 'absolute' // fixed might work as well
}
and then usage (non-jquery) :
document.querySelector('.target').drag();
or in jquery :
$('.target')[0].drag();
Notice : the dragged element should have a position:absolute
or position:fixed
applied to it for the left,top movement to work...
the codepen below has some more "advanced" features : dragStart, dragStop callbacks, css classes appending to remove text selection of other elements while dragging, and a drop feature also...
checkout the following codepen :
http://codepen.io/anon/pen/VPPaEK
its basically setting a 'mousedown' event on the element which needs to be dragged, and then binding and unbinding the document mousemove to handle the movement.
in order to set a draggable handle for the element
Element.prototype.drag = function( setup ){
var setup = setup || {};
var mousemove = function(e){ // document mousemove
this.style.left = ( e.clientX - this.dragStartX ) + 'px';
this.style.top = ( e.clientY - this.dragStartY ) + 'px';
}.bind(this);
var mouseup = function(e){ // document mouseup
document.removeEventListener('mousemove',mousemove);
document.removeEventListener('mouseup',mouseup);
}.bind(this);
var handle = setup.handle || this;
handle.addEventListener('mousedown',function(e){ // element mousedown
this.dragStartX = e.offsetX;
this.dragStartY = e.offsetY;
document.addEventListener('mousemove',mousemove);
document.addEventListener('mouseup',mouseup);
handle.classList.add('dragging');
}.bind(this));
handle.classList.add('draggable');
this.style.position = 'absolute' // fixed might work as well
}
The above code is used like so :
var setup = {
handle : document.querySelector('.handle')
};
document.querySelector('.box').drag(setup);
The problem now, is that when dragging, the text within the draggable element is annoyingly being selected with no use...
This is why we have added the draggable
and dragging
classes to the element. which will cancel out this unwanted behavior, and also add a move cursor, to display that this element is draggable
.draggable{
cursor: move;
position: fixed;
}
.draggable.dragging{
user-select: none;
}
So now that we have our draggable element, we sometimes need to call various events.
setup.ondraginit // this is called when setting up the draggable
setup.ondragstart // this is called when mouse is down on the element
setup.ondragend // this is called when mouse is released (after dragging)
setup.ondrag // this is called while the element is being dragged
Each will pass the original mouse event to the specific handler
Finally, this is what we get...
Element.prototype.drag = function( setup ){
var setup = setup || {};
var mousemove = function(e){ // document mousemove
this.style.left = ( e.clientX - this.dragStartX ) + 'px';
this.style.top = ( e.clientY - this.dragStartY ) + 'px';
setup.ondrag && setup.ondrag(e); // ondrag event
}.bind(this);
var mouseup = function(e){ // document mouseup
document.removeEventListener('mousemove',mousemove);
document.removeEventListener('mouseup',mouseup);
handle.classList.remove('dragging');
setup.ondragend && setup.ondragend(e); // ondragend event
}.bind(this);
var handle = setup.handle || this;
handle.addEventListener('mousedown',function(e){ // element mousedown
this.dragStartX = e.offsetX;
this.dragStartY = e.offsetY;
document.addEventListener('mousemove',mousemove);
document.addEventListener('mouseup',mouseup);
handle.classList.add('dragging');
setup.ondragstart && setup.ondragstart(e); // ondragstart event
}.bind(this));
handle.classList.add('draggable');
setup.ondraginit && setup.ondraginit(e); // ondraginit event
}
And to use this :
var setup = {
handle : document.querySelector('.handle'),
ondragstart : e => { console.log('drag has started!'); },
ondrag : e => { console.log('drag!'); },
ondragend : e => { console.log('drag has ended!'); }
};
document.querySelector('.box').drag(setup);
note that e.target
is a reference back to our draggable element
Content-Type: application/force-download
means "I, the web server, am going to lie to you (the browser) about what this file is so that you will not treat it as a PDF/Word Document/MP3/whatever and prompt the user to save the mysterious file to disk instead". It is a dirty hack that breaks horribly when the client doesn't do "save to disk".
Use the correct mime type for whatever media you are using (e.g. audio/mpeg
for mp3).
Use the Content-Disposition: attachment; etc etc
header if you want to encourage the client to download it instead of following the default behaviour.
If you want the column names of your dataframe, you can use the pyspark.sql
class. I'm not sure if the SDK supports explicitly indexing a DF by column name. I received this traceback:
>>> df.columns['High']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not str
However, calling the columns method on your dataframe, which you have done, will return a list of column names:
df.columns
will return ['Date', 'Open', 'High', 'Low', 'Close', 'Volume', 'Adj Close']
If you want the column datatypes, you can call the dtypes
method:
df.dtypes
will return [('Date', 'timestamp'), ('Open', 'double'), ('High', 'double'), ('Low', 'double'), ('Close', 'double'), ('Volume', 'int'), ('Adj Close', 'double')]
If you want a particular column, you'll need to access it by index:
df.columns[2]
will return 'High'
Classes are simply blueprints to create objects from. The constructor is some code that are run every time you create an object. Therefor it does'nt make sense to have two constructors. What happens is that the second over write the first.
What you typically use them for is create variables for that object like this:
>>> class testing:
... def __init__(self, init_value):
... self.some_value = init_value
So what you could do then is to create an object from this class like this:
>>> testobject = testing(5)
The testobject will then have an object called some_value
that in this sample will be 5.
>>> testobject.some_value
5
But you don't need to set a value for each object like i did in my sample. You can also do like this:
>>> class testing:
... def __init__(self):
... self.some_value = 5
then the value of some_value will be 5 and you don't have to set it when you create the object.
>>> testobject = testing()
>>> testobject.some_value
5
the >>> and ... in my sample is not what you write. It's how it would look in pyshell...
I had been working on this, and I was facing a problem using the responses provided here by different users. Problem was a white box behind my NavigationBar transparent image on iOS 13+
My solution is this one
if #available(iOS 13, *) {
navBar?.standardAppearance.backgroundColor = UIColor.clear
navBar?.standardAppearance.backgroundEffect = nil
navBar?.standardAppearance.shadowImage = UIImage()
navBar?.standardAppearance.shadowColor = .clear
navBar?.standardAppearance.backgroundImage = UIImage()
}
Hope this helps anyone with same problem
Rewriting a file in place is often done by saving the old copy with a modified name. Unix folks add a ~
to mark the old one. Windows folks do all kinds of things -- add .bak or .old -- or rename the file entirely or put the ~ on the front of the name.
import shutil
shutil.move( afile, afile+"~" )
destination= open( aFile, "w" )
source= open( aFile+"~", "r" )
for line in source:
destination.write( line )
if <some condition>:
destination.write( >some additional line> + "\n" )
source.close()
destination.close()
Instead of shutil
, you can use the following.
import os
os.rename( aFile, aFile+"~" )
or you can build one yourself. Open VS, create a new console application. Create a simple project with no ATL or MFC support, leave the stdafx option checked but do not check 'empty project' and call it VersionInfo.
You'll get a simple project with 2 files: VersionInfo.cpp and VersionInfo.h
Open the cpp file and paste the following into it, then compile. You'll be able to run it, first argument is the full filename, it'll print out "Product: 5.6.7.8 File: 1.2.3.4" based on the Version resource block. If there's no version resource it'll return -1, otherwise 0.
Compiles to an 8k binary using the dll CRT, 60k with everything linked statically (set in the C++ options, change "Code Generation page, Runtime options" to "/MT")
HTH.
PS. If you don't want to use Visual Studio, it'll still compile using any c++ compiler (fingers crossed), but you'll almost certainly have to change the #pragma - just specify that lib in the linker settings instead, the pragma's just a shorthand to automatically link with that library.
// VersionInfo.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <windows.h>
#pragma comment(lib, "version.lib")
int _tmain(int argc, _TCHAR* argv[])
{
DWORD handle = 0;
DWORD size = GetFileVersionInfoSize(argv[1], &handle);
BYTE* versionInfo = new BYTE[size];
if (!GetFileVersionInfo(argv[1], handle, size, versionInfo))
{
delete[] versionInfo;
return -1;
}
// we have version information
UINT len = 0;
VS_FIXEDFILEINFO* vsfi = NULL;
VerQueryValue(versionInfo, L"\\", (void**)&vsfi, &len);
WORD fVersion[4], pVersion[4];
fVersion[0] = HIWORD(vsfi->dwFileVersionMS);
fVersion[1] = LOWORD(vsfi->dwFileVersionMS);
fVersion[2] = HIWORD(vsfi->dwFileVersionLS);
fVersion[3] = LOWORD(vsfi->dwFileVersionLS);
pVersion[0] = HIWORD(vsfi->dwProductVersionMS);
pVersion[1] = LOWORD(vsfi->dwProductVersionMS);
pVersion[2] = HIWORD(vsfi->dwProductVersionLS);
pVersion[3] = LOWORD(vsfi->dwProductVersionLS);
printf("Product: %d.%d.%d.%d File: %d.%d.%d.%d\n",
pVersion[0], pVersion[1],
pVersion[2], pVersion[3],
fVersion[0], fVersion[1],
fVersion[2], fVersion[3]);
delete[] versionInfo;
return 0;
}
You could also try setting style
inline without using a variable, like so:
style={{"height" : "100%"}}
or,
for multiple attributes: style={{"height" : "100%", "width" : "50%"}}
{"a":"\u00e1"}
and {"a":"á"}
are different ways to write the same JSON document; The JSON decoder will decode the unicode escape.
In php 5.4+, php's json_encode
does have the JSON_UNESCAPED_UNICODE
option for plain output. On older php versions, you can roll out your own JSON encoder that does not encode non-ASCII characters, or use Pear's JSON encoder and remove line 349 to 433.
I can't remember where I came across this script, but I've been using it with XCloner to move my WP multisites.
<?php
// Setup the associative array for replacing the old string with new string
$replace_array = array( 'FIND' => 'REPLACE', 'FIND' => 'REPLACE');
$mysql_link = mysql_connect( 'localhost', 'USERNAME', 'PASSWORD' );
if( ! $mysql_link) {
die( 'Could not connect: ' . mysql_error() );
}
$mysql_db = mysql_select_db( 'DATABASE', $mysql_link );
if(! $mysql_db ) {
die( 'Can\'t select database: ' . mysql_error() );
}
// Traverse all tables
$tables_query = 'SHOW TABLES';
$tables_result = mysql_query( $tables_query );
while( $tables_rows = mysql_fetch_row( $tables_result ) ) {
foreach( $tables_rows as $table ) {
// Traverse all columns
$columns_query = 'SHOW COLUMNS FROM ' . $table;
$columns_result = mysql_query( $columns_query );
while( $columns_row = mysql_fetch_assoc( $columns_result ) ) {
$column = $columns_row['Field'];
$type = $columns_row['Type'];
// Process only text-based columns
if( strpos( $type, 'char' ) !== false || strpos( $type, 'text' ) !== false ) {
// Process all replacements for the specific column
foreach( $replace_array as $old_string => $new_string ) {
$replace_query = 'UPDATE ' . $table .
' SET ' . $column . ' = REPLACE(' . $column .
', \'' . $old_string . '\', \'' . $new_string . '\')';
mysql_query( $replace_query );
}
}
}
}
}
mysql_free_result( $columns_result );
mysql_free_result( $tables_result );
mysql_close( $mysql_link );
echo 'Done!';
?>
The only thing which worked for me is this
fetchData()
.subscribe(
(data) => {
//Called when success
},
(error) => {
//Called when error
}
).add(() => {
//Called when operation is complete (both success and error)
});
If you are using Spring Security's Java configuration, all of the default security headers are added by default. They can be disabled using the Java configuration below:
@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends
WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.headers().disable()
...;
}
}
As of Java 10, the equivalent is ... var
.
#include <vector>
#include <algorithm>
int main()
{
int arr[5] = {4, 1, 3, 2, 6};
int x = -1;
std::vector<int> testVector(arr, arr + sizeof(arr) / sizeof(int) );
std::vector<int>::iterator it = std::find(testVector.begin(), testVector.end(), 3);
if (it != testVector.end())
{
x = it - testVector.begin();
}
return 0;
}
Or you can just build a vector in a normal way, without creating it from an array of ints and then use the same solution as shown in my example.
f = ... # file-like object, i.e. supporting read(size) function and
# returning empty string '' when there is nothing to read
def chunked(file, chunk_size):
return iter(lambda: file.read(chunk_size), '')
for data in chunked(f, 65536):
# process the data
UPDATE: The approach is best explained in https://stackoverflow.com/a/4566523/38592
To find all local IPv4 addresses:
IPAddress[] ipv4Addresses = Array.FindAll(
Dns.GetHostEntry(string.Empty).AddressList,
a => a.AddressFamily == AddressFamily.InterNetwork);
or use Array.Find
or Array.FindLast
if you just want one.
If you docker registry is private and self hosted you should do the following :
docker login <REGISTRY_HOST>:<REGISTRY_PORT>
docker tag <IMAGE_ID> <REGISTRY_HOST>:<REGISTRY_PORT>/<APPNAME>:<APPVERSION>
docker push <REGISTRY_HOST>:<REGISTRY_PORT>/<APPNAME>:<APPVERSION>
Example :
docker login repo.company.com:3456
docker tag 19fcc4aa71ba repo.company.com:3456/myapp:0.1
docker push repo.company.com:3456/myapp:0.1
Here's what i thought of:
import string
def match(a,b):
a,b = a.lower(), b.lower()
error = 0
for i in string.ascii_lowercase:
error += abs(a.count(i) - b.count(i))
total = len(a) + len(b)
return (total-error)/total
if __name__ == "__main__":
print(match("pple inc", "Apple Inc."))
The simple way to solve the problem is to use ComparisonChain from Guava http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/ComparisonChain.html
private static Comparator<String> stringAlphabeticalComparator = new Comparator<String>() {
public int compare(String str1, String str2) {
return ComparisonChain.start().
compare(str1,str2, String.CASE_INSENSITIVE_ORDER).
compare(str1,str2).
result();
}
};
Collections.sort(list, stringAlphabeticalComparator);
The first comparator from the chain will sort strings according to the case insensitive order, and the second comparator will sort strings according to the case insensitive order. As excepted strings appear in the result according to the alphabetical order:
"AA","Aa","aa","Development","development"
Click the left side dropdown menu "android" and choose "project" to see libs folders
*after choosing project you will see the libs directory
On Windows you may try this:
Use:
set serveroutput on
variable n number
exec :n := dbms_utility.get_time;
select ......
exec dbms_output.put_line( (dbms_utility.get_time-:n)/100) || ' seconds....' );
Or possibly:
SET TIMING ON;
-- do stuff
SET TIMING OFF;
...to get the hundredths of seconds that elapsed.
In either case, time elapsed can be impacted by server load/etc.
Reference:
Your debut
and fin
values are floating point values, not integers, because taille
is a float.
Make those values integers instead:
item = plateau[int(debut):int(fin)]
Alternatively, make taille
an integer:
taille = int(sqrt(len(plateau)))
Netbeans 8.0 (beta at the time of this post) has Angular support as well as HTML5 support.
Check out this Oracle article: https://blogs.oracle.com/geertjan/entry/integrated_angularjs_development
I have combined the James', Howard's and Éder's solutions and created a more generic implementation:
The full code is written bellow (use "DEFINE_ENUM_CLASS_WITH_ToString_METHOD" for defining an enum) (online demo).
#include <boost/preprocessor.hpp>
#include <iostream>
// ADD_PARENTHESES_FOR_EACH_TUPLE_IN_SEQ implementation is taken from:
// http://lists.boost.org/boost-users/2012/09/76055.php
//
// This macro do the following:
// input:
// (Element1, "Element 1 string repr", 2) (Element2) (Element3, "Element 3 string repr")
// output:
// ((Element1, "Element 1 string repr", 2)) ((Element2)) ((Element3, "Element 3 string repr"))
#define HELPER1(...) ((__VA_ARGS__)) HELPER2
#define HELPER2(...) ((__VA_ARGS__)) HELPER1
#define HELPER1_END
#define HELPER2_END
#define ADD_PARENTHESES_FOR_EACH_TUPLE_IN_SEQ(sequence) BOOST_PP_CAT(HELPER1 sequence,_END)
// CREATE_ENUM_ELEMENT_IMPL works in the following way:
// if (elementTuple.GetSize() == 4) {
// GENERATE: elementTuple.GetElement(0) = elementTuple.GetElement(2)),
// } else {
// GENERATE: elementTuple.GetElement(0),
// }
// Example 1:
// CREATE_ENUM_ELEMENT_IMPL((Element1, "Element 1 string repr", 2, _))
// generates:
// Element1 = 2,
//
// Example 2:
// CREATE_ENUM_ELEMENT_IMPL((Element2, _))
// generates:
// Element1,
#define CREATE_ENUM_ELEMENT_IMPL(elementTuple) \
BOOST_PP_IF(BOOST_PP_EQUAL(BOOST_PP_TUPLE_SIZE(elementTuple), 4), \
BOOST_PP_TUPLE_ELEM(0, elementTuple) = BOOST_PP_TUPLE_ELEM(2, elementTuple), \
BOOST_PP_TUPLE_ELEM(0, elementTuple) \
),
// we have to add a dummy element at the end of a tuple in order to make
// BOOST_PP_TUPLE_ELEM macro work in case an initial tuple has only one element.
// if we have a tuple (Element1), BOOST_PP_TUPLE_ELEM(2, (Element1)) macro won't compile.
// It requires that a tuple with only one element looked like (Element1,).
// Unfortunately I couldn't find a way to make this transformation, so
// I just use BOOST_PP_TUPLE_PUSH_BACK macro to add a dummy element at the end
// of a tuple, in this case the initial tuple will look like (Element1, _) what
// makes it compatible with BOOST_PP_TUPLE_ELEM macro
#define CREATE_ENUM_ELEMENT(r, data, elementTuple) \
CREATE_ENUM_ELEMENT_IMPL(BOOST_PP_TUPLE_PUSH_BACK(elementTuple, _))
#define DEFINE_CASE_HAVING_ONLY_ENUM_ELEMENT_NAME(enumName, element) \
case enumName::element : return BOOST_PP_STRINGIZE(element);
#define DEFINE_CASE_HAVING_STRING_REPRESENTATION_FOR_ENUM_ELEMENT(enumName, element, stringRepresentation) \
case enumName::element : return stringRepresentation;
// GENERATE_CASE_FOR_SWITCH macro generates case for switch operator.
// Algorithm of working is the following
// if (elementTuple.GetSize() == 1) {
// DEFINE_CASE_HAVING_ONLY_ENUM_ELEMENT_NAME(enumName, elementTuple.GetElement(0))
// } else {
// DEFINE_CASE_HAVING_STRING_REPRESENTATION_FOR_ENUM_ELEMENT(enumName, elementTuple.GetElement(0), elementTuple.GetElement(1))
// }
//
// Example 1:
// GENERATE_CASE_FOR_SWITCH(_, EnumName, (Element1, "Element 1 string repr", 2))
// generates:
// case EnumName::Element1 : return "Element 1 string repr";
//
// Example 2:
// GENERATE_CASE_FOR_SWITCH(_, EnumName, (Element2))
// generates:
// case EnumName::Element2 : return "Element2";
#define GENERATE_CASE_FOR_SWITCH(r, enumName, elementTuple) \
BOOST_PP_IF(BOOST_PP_EQUAL(BOOST_PP_TUPLE_SIZE(elementTuple), 1), \
DEFINE_CASE_HAVING_ONLY_ENUM_ELEMENT_NAME(enumName, BOOST_PP_TUPLE_ELEM(0, elementTuple)), \
DEFINE_CASE_HAVING_STRING_REPRESENTATION_FOR_ENUM_ELEMENT(enumName, BOOST_PP_TUPLE_ELEM(0, elementTuple), BOOST_PP_TUPLE_ELEM(1, elementTuple)) \
)
// DEFINE_ENUM_CLASS_WITH_ToString_METHOD final macro witch do the job
#define DEFINE_ENUM_CLASS_WITH_ToString_METHOD(enumName, enumElements) \
enum class enumName { \
BOOST_PP_SEQ_FOR_EACH( \
CREATE_ENUM_ELEMENT, \
0, \
ADD_PARENTHESES_FOR_EACH_TUPLE_IN_SEQ(enumElements) \
) \
}; \
inline const char* ToString(const enumName element) { \
switch (element) { \
BOOST_PP_SEQ_FOR_EACH( \
GENERATE_CASE_FOR_SWITCH, \
enumName, \
ADD_PARENTHESES_FOR_EACH_TUPLE_IN_SEQ(enumElements) \
) \
default: return "[Unknown " BOOST_PP_STRINGIZE(enumName) "]"; \
} \
}
DEFINE_ENUM_CLASS_WITH_ToString_METHOD(Elements,
(Element1)
(Element2, "string representation for Element2 ")
(Element3, "Element3 string representation", 1000)
(Element4, "Element 4 string repr")
(Element5, "Element5", 1005)
(Element6, "Element6 ")
(Element7)
)
// Generates the following:
// enum class Elements {
// Element1, Element2, Element3 = 1000, Element4, Element5 = 1005, Element6,
// };
// inline const char* ToString(const Elements element) {
// switch (element) {
// case Elements::Element1: return "Element1";
// case Elements::Element2: return "string representation for Element2 ";
// case Elements::Element3: return "Element3 string representation";
// case Elements::Element4: return "Element 4 string repr";
// case Elements::Element5: return "Element5";
// case Elements::Element6: return "Element6 ";
// case Elements::Element7: return "Element7";
// default: return "[Unknown " "Elements" "]";
// }
// }
int main() {
std::cout << ToString(Elements::Element1) << std::endl;
std::cout << ToString(Elements::Element2) << std::endl;
std::cout << ToString(Elements::Element3) << std::endl;
std::cout << ToString(Elements::Element4) << std::endl;
std::cout << ToString(Elements::Element5) << std::endl;
std::cout << ToString(Elements::Element6) << std::endl;
std::cout << ToString(Elements::Element7) << std::endl;
return 0;
}
As the error message says in the last line: the module models
in the file c:\projects\mysite..\mysite\polls\models.py
contains no class model
. This error occurs in the definition of the Poll
class:
class Poll(models.model):
Either the class model
is misspelled in the definition of the class Poll
or it is misspelled in the module models
. Another possibility is that it is completely missing from the module models
. Maybe it is in another module or it is not yet implemented in models
.
If you want to split/cut the array on an index i,
arr = arr.drop(i)
> arr = [1,2,3,4,5]
=> [1, 2, 3, 4, 5]
> arr.drop(2)
=> [3, 4, 5]
newVariable = originalVariable.valueOf();
for objects you can use,
b = Object.assign({},a);
Did you try using the -ArgumentList
parameter:
invoke-command -ComputerName studio -ScriptBlock { param ( $myarg ) ping.exe $myarg } -ArgumentList localhost
http://technet.microsoft.com/en-us/library/dd347578.aspx
An example of invoking a program that is not in the path and has a space in it's folder path:
invoke-command -ComputerName Computer1 -ScriptBlock { param ($myarg) & 'C:\Program Files\program.exe' -something $myarg } -ArgumentList "myArgValue"
If the value of the argument is static you can just provide it in the script block like this:
invoke-command -ComputerName Computer1 -ScriptBlock { & 'C:\Program Files\program.exe' -something "myArgValue" }
Angular CLI ng v does output few more thing than just the version.
If you only want the version from it the you can add pipe grep and filter for angular like:
ng v | grep 'Angular:'
OUTPUT:
Angular: #.#.# <-- VERSION
For this, I have an alias which is
alias ngv='ng v | grep 'Angular:''
Then just use ngv
inetmgr then come to Application pool->Advanced setting of your pool-> will have the option "Enable 32-Bit Applications" set to true; and restart IIS. check again.!
Even your "long" list is pretty short. Also, did you choose them to match the actual data? Performance will vary with what these data actually look like. For example, you have a short list repeated over and over to make a longer list. This means that the quadratic solution is linear in your benchmarks, but not in reality.
For actually-large lists, the set code is your best bet—it's linear (although space-hungry). The sort and groupby methods are O(n log n) and the loop in method is obviously quadratic, so you know how these will scale as n gets really big. If this is the real size of the data you are analyzing, then who cares? It's tiny.
Incidentally, I'm seeing a noticeable speedup if I don't form an intermediate list to make the set, that is to say if I replace
kt = [tuple(i) for i in k]
skt = set(kt)
with
skt = set(tuple(i) for i in k)
The real solution may depend on more information: Are you sure that a list of lists is really the representation you need?
One way might be;
<select name="listbox" id="listbox">
@foreach (var item in Model)
{
<option value="@item.UserRoleId">
@item.UserRole
</option>
}
</select>
<button id="OpenImgUpload" onclick="$('#imgupload').trigger('click');">Image Upload</button>
<input type="file" id="imgupload" style="display:none"/>
See How to create and apply a patch with Git. (From the wording of your question, I assumed that this other repository is for an entirely different codebase. If it's a repository for the same code base, you should add it as a remote as suggested by @CharlesB. Even if it is for another code base, I guess you could still add it as a remote, but you might not want to get the entire branch into your repository...)
See mine.
func actioncall () {
let loginPageView = self.storyboard?.instantiateViewControllerWithIdentifier("LoginPageID") as! ViewController
self.navigationController?.pushViewController(loginPageView, animated: true)
}
If you use presenting style, you might lose the page's navigation bar with preset pushnavigation.
Assuming:
MacOS Sierra 10.12.5 works as well confirmed by David Rawson and MacOS Sierra 10.12.6 confirmed by Alexander K.
Run the following script in Terminal to create the specific symlink.
ln -s "/Applications/Sublime Text.app/Contents/SharedSupport/bin/subl" /usr/local/bin/subl
Then:
subl .
Hit Return and it should instantly open Sublime Text.
$(function () {
$('.datetimepicker').datetimepicker(
{
format: 'Y-m-d h:m:s'
}
);
});`
Now(in 2020), You could add a base tag in html file.
<head>
<base href="https://www.example.com/static/">
</head>
Define a class for key definition in your group.
class KeyObj {
ArrayList<Object> keys;
public KeyObj( Object... objs ) {
keys = new ArrayList<Object>();
for (int i = 0; i < objs.length; i++) {
keys.add( objs[i] );
}
}
// Add appropriate isEqual() ... you IDE should generate this
}
Now in your code,
peopleByManyParams = people
.collect(Collectors.groupingBy(p -> new KeyObj( p.age, p.other1, p.other2 ), Collectors.mapping((Person p) -> p, toList())));
First you have to click on the report, Then View -> Report Data
Other posters have pointed out how to increase memory and that you could memoize calls. I'd suggest that for many applications, you can use Stirling's formula to approximate large n! very quickly with almost no memory footprint.
Take a gander at this post, which has some analysis of the function and code:
http://threebrothers.org/brendan/blog/stirlings-approximation-formula-clojure/
Use pip download <package1 package2 package n>
to download all the packages including dependencies
Use pip install --no-index --find-links . <package1 package2 package n>
to install all the packages including dependencies.
It gets all the files from CWD
.
It will not download anything
-XX:PermSize
specifies the initial size that will be allocated during startup of the JVM. If necessary, the JVM will allocate up to -XX:MaxPermSize
.
You're misunderstanding the meaning of the merge here.
The --no-commit
prevents the MERGE COMMIT from occuring, and that only happens when you merge two divergent branch histories; in your example that's not the case since Git indicates that it was a "fast-forward" merge and then Git only applies the commits already present on the branch sequentially.
it "should call 'bar' with appropriate arguments" do
expect(subject).to receive(:bar).with("an argument I want")
subject.foo
end
There is also change that Eclipse Project is somehow corrupted. Usually case like this Eclipse is added some duplicated .jars in your project and those .jars are usually same as Maven Dependency .jars.
If your project look like below example there is huge change that Maven Dependencies are duplicated and should be removed manually.
e.g. (Project Explorer View)
src/main/java
src/test/java
spring-boot-vaadin.jar
spring-aop.jar
Maven Dependencies
spring-boot-vaadin.jar
spring-aop.jar
etc...
Just remove all REPO_M2/... paths and update project.
Here is the another way to achive this:
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
item.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
item.setEnabled(true);
item.setTitle(Html.fromHtml("<font color='#ff3824'>Settings</font>"));
return false;
}
});
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
You can use setInterval
:
var timer = setInterval( myFunction, 1000);
Just declare your function as myFunction or some other name, and then don't bind it to $('.more')
's live event.
Instead of calling /usr/bin/gcc
, use /usr/bin/c99
. This is the Single-Unix-approved way of invoking a C99 compiler. On an Ubuntu system, this points to a script which invokes gcc
after having added the -std=c99
flag, which is precisely what you want.
Instead of having a fat APK file, I would like to use just the armeabi files and remove the armeabi-v7a folder.
The opposite is a much better strategy. If you have minSdkVersion
to 14 and upload your apk to the play store, you'll notice you'll support the same number of devices whether you support armeabi
or not. Therefore, there are no devices with Android 4 or higher which would benefit from armeabi
at all.
This is probably why the Android NDK doesn't even support armeabi
anymore as per revision r17b. [source]
This worked for me in Jupyter nOtebook /Mac Platform /Python 3 :
import sys
!{sys.executable} -m pip install -r requirements.txt
The selected answer is: ArrayList<Integer>(Arrays.asList(1,2,3,5,8,13,21));
However, its important to understand the selected answer internally copies the elements several times before creating the final array, and that there is a way to reduce some of that redundancy.
Lets start by understanding what is going on:
First, the elements are copied into the Arrays.ArrayList<T>
created by the static factory Arrays.asList(T...)
.
This does not the produce the same class as java.lang.ArrayList
despite having the same simple class name. It does not implement methods like remove(int)
despite having a List interface. If you call those methods it will throw an UnspportedMethodException
. But if all you need is a fixed-sized list, you can stop here.
Next the Arrays.ArrayList<T>
constructed in #1 gets passed to the constructor ArrayList<>(Collection<T>)
where the collection.toArray()
method is called to clone it.
public ArrayList(Collection<? extends E> collection) {
......
Object[] a = collection.toArray();
}
Next the constructor decides whether to adopt the cloned array, or copy it again to remove the subclass type. Since Arrays.asList(T...)
internally uses an array of type T, the very same one we passed as the parameter, the constructor always rejects using the clone unless T is a pure Object. (E.g. String, Integer, etc all get copied again, because they extend Object).
if (a.getClass() != Object[].class) {
//Arrays.asList(T...) is always true here
//when T subclasses object
Object[] newArray = new Object[a.length];
System.arraycopy(a, 0, newArray, 0, a.length);
a = newArray;
}
array = a;
size = a.length;
Thus, our data was copied 3x just to explicitly initialize the ArrayList. We could get it down to 2x if we force Arrays.AsList(T...)
to construct an Object[] array, so that ArrayList can later adopt it, which can be done as follows:
(List<Integer>)(List<?>) new ArrayList<>(Arrays.asList((Object) 1, 2 ,3, 4, 5));
Or maybe just adding the elements after creation might still be the most efficient.
var lines = ["Mike", "Matt", "Nancy", "Adam", "Jenny", "Nancy", "Carl"];
var uniqueNames = [];
for(var i=0;i<lines.length;i++)
{
if(uniqueNames.indexOf(lines[i]) == -1)
uniqueNames.push(lines[i]);
}
if(uniqueNames.indexOf(uniqueNames[uniqueNames.length-1])!= -1)
uniqueNames.pop();
for(var i=0;i<uniqueNames.length;i++)
{
document.write(uniqueNames[i]);
document.write("<br/>");
}
I had also similar problem where by I had to un-install JDK 1.8 and needed jdk 1.7. What i did was removed the symbolic links from the javapath and then imported the shortcuts of java, javaw, javaws from the bin directory to the javapath folder. However, I found some permission issues in the enterprise laptop where by I did not have the privilege to modify/ update this directory. I had given appropriate permission from the administrator and there by resolved it.
git apply --reverse --reject example.patch
When you created a patch file with the branch names reversed:
ie. git diff feature_branch..master
instead of git diff master..feature_branch
I found the best solution here, the key of this issue is the addEntity method
public static void testSimpleSQL() {
final Session session = sessionFactory.openSession();
SQLQuery q = session.createSQLQuery("select * from ENTITY");
q.addEntity(Entity.class);
List<Entity> entities = q.list();
for (Entity entity : entities) {
System.out.println(entity);
}
}
Note: All of the following instructions apply universally (aka to all OSes) unless otherwise specified.
You will need:
Change the file extension of the .apk
file by either adding a .zip
extension to the filename, or to change .apk
to .zip
.
For example, com.example.apk
becomes com.example.zip
, or com.example.apk.zip
. Note that on Windows and macOS, it may prompt you whether you are sure you want to change the file extension. Click OK or Add if you're using macOS:
Extract the renamed APK file in a specific folder. For example, let that folder be demofolder
.
If it didn't work, try opening the file in another application such as WinZip or 7-Zip.
For macOS, you can try running unzip
in Terminal (available at /Applications/Terminal.app
), where it takes one or more arguments: the file to unzip + optional arguments. See man unzip
for documentation and arguments.
Download dex2jar
(see all releases on GitHub) and extract that zip file in the same folder as stated in the previous point.
Open command prompt (or a terminal) and change your current directory to the folder created in the previous point and type the command d2j-dex2jar.bat classes.dex
and press enter. This will generate classes-dex2jar.jar
file in the same folder.
d2j-dex2jar.bat
with d2j-dex2jar.sh
. In other words, run d2j-jar2dex.sh classes.dex
in the terminal and press enter.Download Java Decompiler (see all releases on Github) and extract it and start (aka double click) the executable/application.
From the JD-GUI window, either drag and drop the generated classes-dex2jar.jar
file into it, or go to File > Open File...
and browse for the jar.
Next, in the menu, go to File > Save All Sources
(Windows: Ctrl+Alt+S, macOS: ?+?+S). This should open a dialog asking you where to save a zip file named `classes-dex2jar.jar.src.zip" consisting of all packages and java files. (You can rename the zip file to be saved)
Extract that zip file (classes-dex2jar.jar.src.zip
) and you should get all java files of the application.
xml
files from APKapktool
website for installation instructions and moreWindows:
myxmlfolder
).myxmlfolder
folder and rename the apktool jar file to apktool.jar
..apk
file in the same folder (i.e myxmlfolder
).Open the command prompt (or terminal) and change your current directory to the folder where apktool
is stored (in this case, myxmlfolder
). Next, type the command apktool if framework-res.apk
.
What we're doing here is that we are installing a framework. For more info, see the docs.
In the command prompt, type the command apktool d filename.apk
(where filename
is the name of apk file). This should decode the file. For more info, see the docs.
This should result in a folder filename.out
being outputted, where filename
is the original name of the apk file without the .apk
file extension. In this folder are all the XML files such as layout, drawables etc.
Source: How to get source code from APK file - Comptech Blogspot
I had a similar issue when adding a class to the main method. Turns out it wasn't an issue, it was me not checking my spelling. So, as a noob, I learned that mis-spelling can and will mess things up. These posts helped me "see" my mistake and all is good now.
Also, if your service is sending an object instead of an array add isArray:false to its declaration.
'query': {method: 'GET', isArray: false }
Isn't it better with a group by? Something like:
SELECT COUNT(*) FROM t1 GROUP BY keywork;
if you are using maven:
mvn eclipse:eclipse -DdownloadSources=true -DdownloadJavadocs=true
According to me: For files, use lower camel case if module.exports is an object, I mean a singleton module. This is also applicable to JSON files as they are also in a way single ton. Use upper camel case if module.exports returns a constructor function where it acts like a class.
For folders use short names. If there is need to have multiple words, let it be completely lower case separated by "-" so that it works across all platforms consistently.
I'm adding this answer (for myself) as relevant to custom formatting.
For underscore yyyy_MM_dd
REPLACE(SUBSTRING(CONVERT(VARCHAR, @dt, 120), 1, 10),'-','_')
If you encounter this apparent index corruption in a running system, you can work around it by deleting all files called segments.gen. It is advisory only, and Lucene can recover correctly without it.
From ElasticSearch Blog
Press the start button in visual studio. Then go to the location where your solution is stored and open the folder of your main project then the bin folder. If your application was running in debug mode then go to the debug folder. If running in release mode then go to the release folder. You should find your exe there.
linterOptions is currently only handled by the CLI. If you're not using CLI then depending on the code base you're using you'll need to set the ignore somewhere else. webpack, tsconfig, etc
Simply restate the target field & condition;
where (field like "*AA*" and field not like "*BB*")
You can use the str.split
method: string.split('__')
>>> "MATCHES__STRING".split("__")
['MATCHES', 'STRING']