View the source of the login page. Look for the form
HTML tag. Within that tag is something that will look like action=
Use that value as $url
, not the URL of the form itself.
Also, while you are there, verify the input boxes are named what you have them listed as.
For example, a basic login form will look similar to:
<form method='post' action='postlogin.php'>
Email Address: <input type='text' name='email'>
Password: <input type='password' name='password'>
</form>
Using the above form as an example, change your value of $url
to:
$url="http://www.myremotesite.com/postlogin.php";
Verify the values you have listed in $postdata
:
$postdata = "email=".$username."&password=".$password;
and it should work just fine.
To clarify which command to use based on the situation
exec()
- Execute an external program
system()
- Execute an external program and display the output
passthru()
- Execute an external program and display raw output
I know this question is old, but no one has mentioned a native solution yet. If you're not trying to support archaic browsers (which you shouldn't be at this point), you can use array.filter
:
var arr = [];_x000D_
arr.push({name:"k1", value:"abc"});_x000D_
arr.push({name:"k2", value:"hi"});_x000D_
arr.push({name:"k3", value:"oa"});_x000D_
_x000D_
var found = arr.filter(function(item) { return item.name === 'k1'; });_x000D_
_x000D_
console.log('found', found[0]);
_x000D_
Check the console.
_x000D_
You can see a list of supported browsers here.
In the future with ES6, you'll be able to use array.find.
To add to Matt wilson's answer I had a bunch of code-first entity classes but no database as I hadn't taken a backup. So I did the following on my Entity Framework project:
Open Package Manager console in Visual Studio and type the following:
Enable-Migrations
Add-Migration
Give your migration a name such as 'Initial' and then create the migration. Finally type the following:
Update-Database
Update-Database -Script -SourceMigration:0
The final command will create your database tables from your entity classes (provided your entity classes are well formed).
Open git repository on browser, got to "Setttings", you can see rename button.
Input new "Repository Name" and click "Rename" button.
The jQuery.getScript()
method is a shorthand of the Ajax function (with the dataType attribute: $.ajax({ url: url,
dataType: "script"
})
)
If you want the scripts to be cachable, either use RequireJS or follow jQuery's example on extending the jQuery.getScript
method similar to the following.
jQuery.cachedScript = function( url, options ) {
// Allow user to set any option except for dataType, cache, and url
options = $.extend( options || {}, {
dataType: "script",
cache: true,
url: url
});
// Use $.ajax() since it is more flexible than $.getScript
// Return the jqXHR object so we can chain callbacks
return jQuery.ajax( options );
};
// Usage
$.cachedScript( "ajax/test.js" ).done(function( script, textStatus ) {
console.log( textStatus );
});
See section Attributes from documentation on directives.
observing interpolated attributes: Use $observe to observe the value changes of attributes that contain interpolation (e.g. src="{{bar}}"). Not only is this very efficient but it's also the only way to easily get the actual value because during the linking phase the interpolation hasn't been evaluated yet and so the value is at this time set to undefined.
Here are the various ways you may pull this (depending on your needs).
Using the Time DataType:
DECLARE @Time Time = '15:04:46.217'
SELECT --'3:04PM'
CONVERT(VarChar(7), @Time, 0),
--' 3:04PM' --Leading Space.
RIGHT(' ' + CONVERT(VarChar(7), @Time, 0), 7),
--' 3:04 PM' --Space before AM/PM.
STUFF(RIGHT(' ' + CONVERT(VarChar(7), @Time, 0), 7), 6, 0, ' '),
--'03:04 PM' --Leading Zero. This answers the question above.
STUFF(RIGHT('0' + CONVERT(VarChar(7), @Time, 0), 7), 6, 0, ' ')
--'03:04 PM' --This only works in SQL Server 2012 and above. :)
,FORMAT(CAST(@Time as DateTime), 'hh:mm tt')--Comment out for SS08 or less.
Using the DateTime DataType:
DECLARE @Date DateTime = '2016-03-17 15:04:46.217'
SELECT --' 3:04PM' --No space before AM/PM.
RIGHT(CONVERT(VarChar(19), @Date, 0), 7),
--' 3:04 PM' --Space before AM/PM.
STUFF(RIGHT(CONVERT(VarChar(19), @Date, 0), 7), 6, 0, ' '),
--'3:04 PM' --No Leading Space.
LTRIM(STUFF(RIGHT(CONVERT(VarChar(19), @Date, 0), 7), 6, 0, ' ')),
--'03:04 PM' --Leading Zero.
STUFF(REPLACE(RIGHT(CONVERT(VarChar(19), @Date, 0), 7), ' ', '0'), 6, 0, ' ')
--'03:04 PM' --This only works in SQL Server 2012 and above. :)
,FORMAT(@Date, 'hh:mm tt')--Comment line out for SS08 or less.
#if DEBUG
bool bypassCheck=TRUE_OR_FALSE;//i will decide depending on what i am debugging
#else
bool bypassCheck = false; //NEVER bypass it
#endif
Make sure you have the checkbox to define DEBUG checked in your build properties.
If you are trying to get the id, then please update your code like
html += '<option id = "' + n.id + "' value="' + i + '">' + n.names + '</option>';
To retrieve id,
$('option:selected').attr("id")
To retrieve Value
$('option:selected').val()
in Javascript
var e = document.getElementById("jobSel");
var job = e.options[e.selectedIndex].value;
Note that the use of unescape()
is deprecated and doesn't work with the TypeScript compiler, for example.
Based on radicand's answer and the comments section below, here's an updated solution:
var string = "http\\u00253A\\u00252F\\u00252Fexample.com";
decodeURIComponent(JSON.parse('"' + string.replace(/\"/g, '\\"') + '"'));
http://example.com
Ensure that binary files are under "bin" subdirectory of your ".svc" file
In Swift 3.0
let screenSize = UIScreen.main.bounds
let screenWidth = screenSize.width
let screenHeight = screenSize.height
In older swift: Do something like this:
let screenSize: CGRect = UIScreen.mainScreen().bounds
then you can access the width and height like this:
let screenWidth = screenSize.width
let screenHeight = screenSize.height
if you want 75% of your screen's width you can go:
let screenWidth = screenSize.width * 0.75
Swift 4.0
// Screen width.
public var screenWidth: CGFloat {
return UIScreen.main.bounds.width
}
// Screen height.
public var screenHeight: CGFloat {
return UIScreen.main.bounds.height
}
In Swift 5.0
let screenSize: CGRect = UIScreen.main.bounds
The problem seems to be that you have misunderstood how async/await work with Entity Framework.
So, let's look at this code:
public IQueryable<URL> GetAllUrls()
{
return context.Urls.AsQueryable();
}
and example of it usage:
repo.GetAllUrls().Where(u => <condition>).Take(10).ToList()
What happens there?
IQueryable
object (not accessing database yet) using repo.GetAllUrls()
IQueryable
object with specified condition using .Where(u => <condition>
IQueryable
object with specified paging limit using .Take(10)
.ToList()
. Our IQueryable
object is compiled to sql (like select top 10 * from Urls where <condition>
). And database can use indexes, sql server send you only 10 objects from your database (not all billion urls stored in database)Okay, let's look at first code:
public async Task<IQueryable<URL>> GetAllUrlsAsync()
{
var urls = await context.Urls.ToListAsync();
return urls.AsQueryable();
}
With the same example of usage we got:
await context.Urls.ToListAsync();
.Why async/await is preferred to use? Let's look at this code:
var stuff1 = repo.GetStuff1ForUser(userId);
var stuff2 = repo.GetStuff2ForUser(userId);
return View(new Model(stuff1, stuff2));
What happens here?
var stuff1 = ...
userId
var stuff2 = ...
userId
So let's look to an async version of it:
var stuff1Task = repo.GetStuff1ForUserAsync(userId);
var stuff2Task = repo.GetStuff2ForUserAsync(userId);
await Task.WhenAll(stuff1Task, stuff2Task);
return View(new Model(stuff1Task.Result, stuff2Task.Result));
What happens here?
So good code here:
using System.Data.Entity;
public IQueryable<URL> GetAllUrls()
{
return context.Urls.AsQueryable();
}
public async Task<List<URL>> GetAllUrlsByUser(int userId) {
return await GetAllUrls().Where(u => u.User.Id == userId).ToListAsync();
}
Note, than you must add using System.Data.Entity
in order to use method ToListAsync()
for IQueryable.
Note, that if you don't need filtering and paging and stuff, you don't need to work with IQueryable
. You can just use await context.Urls.ToListAsync()
and work with materialized List<Url>
.
Behind the curtain, enums are POJOs with a private constructor and a bunch of public static final values of the enum's type (see here for an example). In fact, up until Java5, it was considered best-practice to build your own enumeration this way, and Java5 introduced the enum
keyword as a shorthand. See the source for Enum<T> to learn more.
So it should be no problem to write your own 'TypeSafeEnum' with a public static final array of constants, that are read by the constructor or passed to it.
Also, do yourself a favor and override equals
, hashCode
and toString
, and if possible create a values
method
The question is how to use such a dynamic enumeration... you can't read the value "PI=3.14" from a file to create enum MathConstants
and then go ahead and use MathConstants.PI
wherever you want...
int atoi(const char* str){
int num = 0;
int i = 0;
bool isNegetive = false;
if(str[i] == '-'){
isNegetive = true;
i++;
}
while (str[i] && (str[i] >= '0' && str[i] <= '9')){
num = num * 10 + (str[i] - '0');
i++;
}
if(isNegetive) num = -1 * num;
return num;
}
ADB Connect to wifi with credentials :
You can use the following ADB command to connect to wifi and enter password as well :
adb wait-for-device shell am start -n com.android.settingstest/.wifi.WifiSettings -e WIFI 1 -e AccessPointName "enter_user_name" -e Password "enter_password"
Had the same problem, but restarting Visual Studio every time was no option for me, as the issue occurs sometimes very often.
I handled it by installing Unlocker (tries to install any toolbar at installation, so don't forget to uncheck this), this application gives me fast access to rename/delete a locked ".xml"-File. I know that this only a workaround too, but for me it was the fastest solution to solve this problem.
<div id="app">
<a :href="path" />Link</a>
</div>
<script>
new Vue({
el: '#app',
data: {
path: 'https://www.google.com/'
}
});
</script> enter code here
This is how i solve my problem
let parameters = [
"station_id" : "1000",
"title": "Murat Akdeniz",
"body": "xxxxxx"]
let imgData = UIImageJPEGRepresentation(UIImage(named: "1.png")!,1)
Alamofire.upload(
multipartFormData: { MultipartFormData in
// multipartFormData.append(imageData, withName: "user", fileName: "user.jpg", mimeType: "image/jpeg")
for (key, value) in parameters {
MultipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
}
MultipartFormData.append(UIImageJPEGRepresentation(UIImage(named: "1.png")!, 1)!, withName: "photos[1]", fileName: "swift_file.jpeg", mimeType: "image/jpeg")
MultipartFormData.append(UIImageJPEGRepresentation(UIImage(named: "1.png")!, 1)!, withName: "photos[2]", fileName: "swift_file.jpeg", mimeType: "image/jpeg")
}, to: "http://platform.twitone.com/station/add-feedback") { (result) in
switch result {
case .success(let upload, _, _):
upload.responseJSON { response in
print(response.result.value)
}
case .failure(let encodingError): break
print(encodingError)
}
}
All of the above might be true, however for me "online-updating" of figures only works with some backends, specifically wx
. You just might try to change to this, e.g. by starting ipython/pylab by ipython --pylab=wx
! Good luck!
Setting the -fx-text-fill
works for me.
See below:
if (passed) {
resultInfo.setText("Passed!");
resultInfo.setStyle("-fx-text-fill: green; -fx-font-size: 16px;");
} else {
resultInfo.setText("Failed!");
resultInfo.setStyle("-fx-text-fill: red; -fx-font-size: 16px;");
}
You can update the output folder in .angular-cli.json:
"outDir": "./location/toYour/dist"
This is an older question, but if you simply want to run the simulator from the Xcode 4.5 UI, you can do: Xcode > Open Developer Tool > iOS Simulator.
For me the problem had caused due to "’" that symbol in the quotes. As i had copied the code from a pdf file it caused that error. I just replaced "’" by this "'".
This works if you want the first element, like my_list.get(0)
>>> my_list = [1,2,3]
>>> next(iter(my_list), 'fail')
1
>>> my_list = []
>>> next(iter(my_list), 'fail')
'fail'
I know it's not exactly what you asked for but it might help others.
If you mean you want the background image itself to be offset by 50 pixels from the top, like a background margin, then just switch out the top
for 50px
and you're set.
#thedivstatus {
background-image: url("imagestatus.gif");
background-position: right 50px;
background-repeat: no-repeat;
}
This works for me in Java 1.5 - I stripped out specific exceptions for readability.
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import java.io.ByteArrayInputStream;
public Document loadXMLFromString(String xml) throws Exception
{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
return builder.parse(new ByteArrayInputStream(xml.getBytes()));
}
Solution to the original question
You called a non-static method statically. To make a public function static in the model, would look like this:
public static function {
}
In General:
Post::get()
In this particular instance:
Post::take(2)->get()
One thing to be careful of, when defining relationships and scope, that I had an issue with that caused a 'non-static method should not be called statically' error is when they are named the same, for example:
public function category(){
return $this->belongsTo('App\Category');
}
public function scopeCategory(){
return $query->where('category', 1);
}
When I do the following, I get the non-static error:
Event::category()->get();
The issue, is that Laravel is using my relationship method called category, rather than my category scope (scopeCategory). This can be resolved by renaming the scope or the relationship. I chose to rename the relationship:
public function cat(){
return $this->belongsTo('App\Category', 'category_id');
}
Please observe that I defined the foreign key (category_id) because otherwise Laravel would have looked for cat_id instead, and it wouldn't have found it, as I had defined it as category_id in the database.
I have done for
private void addOrRemoveProperty(View view, int property, boolean flag){
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) view.getLayoutParams();
if(flag){
layoutParams.addRule(property);
}else {
layoutParams.removeRule(property);
}
view.setLayoutParams(layoutParams);
}
How to call method:
centerInParent - true
addOrRemoveProperty(mView, RelativeLayout.CENTER_IN_PARENT, true);
centerInParent - false
addOrRemoveProperty(mView, RelativeLayout.CENTER_IN_PARENT, false);
centerHorizontal - true
addOrRemoveProperty(mView, RelativeLayout.CENTER_HORIZONTAL, true);
centerHorizontal - false
addOrRemoveProperty(mView, RelativeLayout.CENTER_HORIZONTAL, false);
centerVertical - true
addOrRemoveProperty(mView, RelativeLayout.CENTER_VERTICAL, true);
centerVertical - false
addOrRemoveProperty(mView, RelativeLayout.CENTER_VERTICAL, false);
Hope this would help you.
Send XML requests with the raw
data type, then set the Content-Type to text/xml
.
After creating a request, use the dropdown to change the request type to POST.
Open the Body tab and check the data type for raw.
Open the Content-Type selection box that appears to the right and select either XML (application/xml) or XML (text/xml)
Enter your raw XML data into the input field below
Click Send to submit your XML Request to the specified server.
It may be a little late for the original question but for future queries this might help. Best way to achieve this is Get the result of the inner query to an array like this
$this->db->select('id');
$result = $this->db->get('your_table');
return $result->result_array();
And then use than array in the following active record clause
$this->db->where_not_in('id_of_another_table', 'previously_returned_array');
Hope this helps
For Windows Users:
If the python
command is not in your $PATH
environment var.
Open PowerShell and run these commands to find the folder
cd \
ls *ython* -Recurse -Directory
That should tell you where python is installed
Louis' answer is great, but I thought I would try to sum it up succinctly:
The bang operator tells the compiler to temporarily relax the "not null" constraint that it might otherwise demand. It says to the compiler: "As the developer, I know better than you that this variable cannot be null right now".
Might not be the case, but this was the solution to my "pre-receive hook declined" error:
There are some repositories that only allow modifications through Pull Request. This means that you have to
Solution with awk:
awk '{if ($1 ~ /^all/) print $0, "anotherthing"; else print $0}' file
Simply: if the row starts with all
print the row plus "anotherthing", else print just the row.
I had a scenario where nested JSON had to be serialised in a linear fashion while form data is constructed, since this is how server expects values. So, I wrote a small recursive function which translates the JSON which is like this:
{
"orderPrice":"11",
"cardNumber":"************1234",
"id":"8796191359018",
"accountHolderName":"Raj Pawan",
"expiryMonth":"02",
"expiryYear":"2019",
"issueNumber":null,
"billingAddress":{
"city":"Wonderland",
"code":"8796682911767",
"firstname":"Raj Pawan",
"lastname":"Gumdal",
"line1":"Addr Line 1",
"line2":null,
"state":"US-AS",
"region":{
"isocode":"US-AS"
},
"zip":"76767-6776"
}
}
Into something like this:
{
"orderPrice":"11",
"cardNumber":"************1234",
"id":"8796191359018",
"accountHolderName":"Raj Pawan",
"expiryMonth":"02",
"expiryYear":"2019",
"issueNumber":null,
"billingAddress.city":"Wonderland",
"billingAddress.code":"8796682911767",
"billingAddress.firstname":"Raj Pawan",
"billingAddress.lastname":"Gumdal",
"billingAddress.line1":"Addr Line 1",
"billingAddress.line2":null,
"billingAddress.state":"US-AS",
"billingAddress.region.isocode":"US-AS",
"billingAddress.zip":"76767-6776"
}
The server would accept form data which is in this converted format.
Here is the function:
function jsonToFormData (inJSON, inTestJSON, inFormData, parentKey) {
// http://stackoverflow.com/a/22783314/260665
// Raj: Converts any nested JSON to formData.
var form_data = inFormData || new FormData();
var testJSON = inTestJSON || {};
for ( var key in inJSON ) {
// 1. If it is a recursion, then key has to be constructed like "parent.child" where parent JSON contains a child JSON
// 2. Perform append data only if the value for key is not a JSON, recurse otherwise!
var constructedKey = key;
if (parentKey) {
constructedKey = parentKey + "." + key;
}
var value = inJSON[key];
if (value && value.constructor === {}.constructor) {
// This is a JSON, we now need to recurse!
jsonToFormData (value, testJSON, form_data, constructedKey);
} else {
form_data.append(constructedKey, inJSON[key]);
testJSON[constructedKey] = inJSON[key];
}
}
return form_data;
}
Invocation:
var testJSON = {};
var form_data = jsonToFormData (jsonForPost, testJSON);
I am using testJSON just to see the converted results since I would not be able to extract the contents of form_data. AJAX post call:
$.ajax({
type: "POST",
url: somePostURL,
data: form_data,
processData : false,
contentType : false,
success: function (data) {
},
error: function (e) {
}
});
In Swift 4 and latter
let count = 50//For example
for i in (1...count).reversed() {
print(i)
}
Update null elements with value in the same location in other. Combines a DataFrame with other DataFrame using func to element-wise combine columns. The row and column indexes of the resulting DataFrame will be the union of the two.
df1 = pd.DataFrame({'A': [None, 0], 'B': [None, 4]})
df2 = pd.DataFrame({'A': [1, 1], 'B': [3, 3]})
df1.combine_first(df2)
A B
0 1.0 3.0
1 0.0 4.0
select index_name, column_name
from user_ind_columns
where table_name = 'NAME';
OR use this:
select TABLE_NAME, OWNER
from SYS.ALL_TABLES
order by OWNER, TABLE_NAME
And for Indexes:
select INDEX_NAME, TABLE_NAME, TABLE_OWNER
from SYS.ALL_INDEXES
order by TABLE_OWNER, TABLE_NAME, INDEX_NAME
I would use min/max
(and not worry otherwise) ... however, here is another "long hand" approach which may or may not be easier for some people to understand. (I would not expect it to be faster or slower than the code in the post.)
int smallest;
if (a < b) {
if (a > c) {
smallest = c;
} else { // a <= c
smallest = a;
}
} else { // a >= b
if (b > c) {
smallest = c;
} else { // b <= c
smallest = b;
}
}
Just throwing it into the mix.
Note that this is just the side-effecting variant of Abhishek's answer.
this works:
window.onscroll = function (e) {
// called when the window is scrolled.
}
edit:
you said this is a function in a TimeInterval..
Try doing it like so:
userHasScrolled = false;
window.onscroll = function (e)
{
userHasScrolled = true;
}
then inside your Interval insert this:
if(userHasScrolled)
{
//do your code here
userHasScrolled = false;
}
The route-map express example matches url paths with objects which in turn matches http verbs with functions. This lays the routing out in a tree, which is concise and easy to read. The apps's entities are also written as objects with the functions as enclosed methods.
var express = require('../../lib/express')
, verbose = process.env.NODE_ENV != 'test'
, app = module.exports = express();
app.map = function(a, route){
route = route || '';
for (var key in a) {
switch (typeof a[key]) {
// { '/path': { ... }}
case 'object':
app.map(a[key], route + key);
break;
// get: function(){ ... }
case 'function':
if (verbose) console.log('%s %s', key, route);
app[key](route, a[key]);
break;
}
}
};
var users = {
list: function(req, res){
res.send('user list');
},
get: function(req, res){
res.send('user ' + req.params.uid);
},
del: function(req, res){
res.send('delete users');
}
};
var pets = {
list: function(req, res){
res.send('user ' + req.params.uid + '\'s pets');
},
del: function(req, res){
res.send('delete ' + req.params.uid + '\'s pet ' + req.params.pid);
}
};
app.map({
'/users': {
get: users.list,
del: users.del,
'/:uid': {
get: users.get,
'/pets': {
get: pets.list,
'/:pid': {
del: pets.del
}
}
}
}
});
app.listen(3000);
Android Studio 3.2
Blazingly fast :P
Just Copy and Paste in this folder
that because you calling toggle inside the render method which will cause to re-render and toggle will call again and re-rendering again and so on
this line at your code
{<td><span onClick={this.toggle()}>Details</span></td>}
you need to make onClick
refer to this.toggle
not calling it
to fix the issue do this
{<td><span onClick={this.toggle}>Details</span></td>}
U+F0FE ?
is not a checkbox, it's a Private Use Area character that might render as anything. Whilst you can certainly try to include it in an HTML document, either directly in a UTF-8 document, or as a character reference like 
, you shouldn't expect it to render as a checkbox. It certainly doesn't on any of my browsers—although on some the ‘unknown character’ glyph is a square box that at least looks similar!
So where does U+F0FE come from? It is an unfortunate artifact of Word RTF export where the original document used a symbol font: one with no standard mapping to normal unicode characters; specifically, in this case, Wingdings. If you need to accept Word RTF from documents still authored with symbol fonts, then you will need to map those symbol characters to proper Unicode characters. Unfortunately that's tricky as it requires you to know the particular symbol font and have a map for it. See this post for background.
The standardised Unicode characters that best represent a checkbox are:
?
, U+2610 Ballot box?
, U+2611 Ballot box with checkIf you don't have a Unicode-safe editor you can naturally spell them as ☐
and ☑
.
(There is also U+2612 using an X, ?
.)
Remove dist folder and this solve my problem!!
Make the submit button the main image you are using. So the form tags would come first then submit button which is your only image so the image is your clickable image form. Then just make sure to put whatever you are passing before the submit button code.
Either the parameter supplied for ZIP_CODE
is larger (in length) than ZIP_CODE
s column width or the parameter supplied for CITY
is larger (in length) than CITY
s column width.
It would be interesting to know the values supplied for the two ?
placeholders.
The simplest way, with circular reference handling and all:
function dump(t, indent, done)
done = done or {}
indent = indent or 0
done[t] = true
for key, value in pairs(t) do
print(string.rep("\t", indent))
if (type(value) == "table" and not done[value]) then
done[value] = true
print(key, ":\n")
dump(value, indent + 2, done)
done[value] = nil
else
print(key, "\t=\t", value, "\n")
end
end
end
If this happens in visual studio then clean your project and run it again.
Build --> Clean Solution
Run (or F5)
There is a free python tool called YouTube transcript API
You can use it in scripts or as a command line tool:
pip install youtube_transcript_api
for .NET Core console apps you can do this 2 ways - from the launchsettings.json or the properties menu.
Launchsettings.json
or right click the project > properties > debug tab on left
see "Application Arguments:"
Using $rootScope.$broadcast and $scope.$on for a PubSub communication.
Also, see this post: AngularJS – Communicating Between Controllers
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<mvc:default-servlet-handler/>
</beans>
and if you want to use annotation based configuration use below code
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
you first would need to convert string into datetime tuple, and then convert that datetime tuple to string, it would go like this:
lastconnection = datetime.strptime("21/12/2008", "%d/%m/%Y").strftime('%Y-%m-%d')
if ComboBoxStyle
is set to DropDownList
then the easiest way to make sure the user selects an item is to set SelectedIndex = -1
, which will be empty
Query to find the 2nd highest number in a row-
select Top 1 (salary) from XYZ
where Salary not in (select distinct TOP 1(salary) from XYZ order by Salary desc)
ORDER BY Salary DESC
By changing the highlighted Top 1
to TOP 2
, 3
or 4
u can find the 3rd, 4th and 5th highest respectively.
2019 Update:
While Python-iOS development is relatively immature and likely will prevent (afaik) your app from having native UI and functionality that could be achieved in an Apple-supported development language, Apple now seems to allow embedding Python interpreters in Native Swift/Obj-C apps.
This supports importing Python libraries and running Python scripts (even with supplied command-line arguments) directly from your Native Swift/Obj-C code.
My company is actually wrapping our infrastructure (originally written in Python) in a native iOS application! It works very well and communication between the parts can be easily achieved via a client-server model.
Here is a nice library by Beeware with a cookiecutter template if you want to try and run Python scripts in your iOS app: https://github.com/beeware/Python-Apple-support/tree/3.6.
The keyword super
doesn't "stick". Every method call is handled individually, so even if you got to SuperClass.method1()
by calling super
, that doesn't influence any other method call that you might make in the future.
That means there is no direct way to call SuperClass.method2()
from SuperClass.method1()
without going though SubClass.method2()
unless you're working with an actual instance of SuperClass
.
You can't even achieve the desired effect using Reflection (see the documentation of java.lang.reflect.Method.invoke(Object, Object...)
).
[EDIT] There still seems to be some confusion. Let me try a different explanation.
When you invoke foo()
, you actually invoke this.foo()
. Java simply lets you omit the this
. In the example in the question, the type of this
is SubClass
.
So when Java executes the code in SuperClass.method1()
, it eventually arrives at this.method2();
Using super
doesn't change the instance pointed to by this
. So the call goes to SubClass.method2()
since this
is of type SubClass
.
Maybe it's easier to understand when you imagine that Java passes this
as a hidden first parameter:
public class SuperClass
{
public void method1(SuperClass this)
{
System.out.println("superclass method1");
this.method2(this); // <--- this == mSubClass
}
public void method2(SuperClass this)
{
System.out.println("superclass method2");
}
}
public class SubClass extends SuperClass
{
@Override
public void method1(SubClass this)
{
System.out.println("subclass method1");
super.method1(this);
}
@Override
public void method2(SubClass this)
{
System.out.println("subclass method2");
}
}
public class Demo
{
public static void main(String[] args)
{
SubClass mSubClass = new SubClass();
mSubClass.method1(mSubClass);
}
}
If you follow the call stack, you can see that this
never changes, it's always the instance created in main()
.
You can use the click
event and call your function or move your logic into the handler:
$("#bfCaptchaEntry").click(function(){ myFunction(); });
You can use the click
event and set your function as the handler:
$("#bfCaptchaEntry").click(myFunction);
.click()
Bind an event handler to the "click" JavaScript event, or trigger that event on an element.
You can use the on
event bound to "click"
and call your function or move your logic into the handler:
$("#bfCaptchaEntry").on("click", function(){ myFunction(); });
You can use the on
event bound to "click"
and set your function as the handler:
$("#bfCaptchaEntry").on("click", myFunction);
.on()
Attach an event handler function for one or more events to the selected elements.
My train data contains three features are object after applying astype
it converts the object into numeric but before that, you need to perform some preprocessing steps:
train.dtypes
C12 object
C13 object
C14 Object
train['C14'] = train.C14.astype(int)
train.dtypes
C12 object
C13 object
C14 int32
The following code should allow you to check for the existance of the header you're after in Request.Headers
:
if (Request.Headers.AllKeys.Contains("XYZComponent"))
{
// Can now check if the value is true:
var value = Convert.ToBoolean(Request.Headers["XYZComponent"]);
}
Thanks to RandomUs 1r for this observation:
changing it to display:inline-block; solves that issue. – RandomUs1r May 14 '13 at 21:59
I tried it myself for a top navigation menu bar, as follows:
First style the "li" element as follows:
display: inline-block;
width: 7em;
text-align: center;
Then style the "a"> element as follows:
width: 100%;
Now the navigation links are all equal width with text centered in each link.
You can use this.getClass().getSimpleName()
, like so:
import java.lang.reflect.Field;
public class Test {
int x;
int y;
public void getClassName() {
String className = this.getClass().getSimpleName();
System.out.println("Name:" + className);
}
public void getAttributes() {
Field[] attributes = this.getClass().getDeclaredFields();
for(int i = 0; i < attributes.length; i++) {
System.out.println("Declared Fields" + attributes[i]);
}
}
public static void main(String args[]) {
Test t = new Test();
t.getClassName();
t.getAttributes();
}
}
Replace version code with appropriate code of library version will solve your issue, like this:
<integer name="google_play_services_version"> <versioncode> </integer>
I have a test application set up using JPA/Hibernate & Spring, and my configuration mirrors yours with the exception that I create a datasource and inject it into the EntityManagerFactory, and moved the datasource specific properties out of the persistenceUnit and into the datasource. With these two small changes, my EM gets injected properly.
Public variable declarations in classes is the easiest way:
On target class:
public class MyFragment extends Fragment {
public MyCallerFragment caller; // Declare the caller var
...
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Do what you want with the vars
caller.str = "I changed your value!";
caller.i = 9999;
...
return inflater.inflate(R.layout.my_fragment, container, false);
}
...
}
On caller class:
public class MyCallerFragment extends Fragment {
public Integer i; // Declared public var
public String str; // Declared public var
...
FragmentManager fragmentManager = getParentFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
myFragment = new MyFragment();
myFragment.caller = this;
transaction.replace(R.id.nav_host_fragment, myFragment)
.addToBackStack(null).commit();
...
}
If you want to use the main activity it is easy too:
On main activity class:
public class MainActivity extends AppCompatActivity {
public String str; // Declare public var
public EditText myEditText; // You can declare public elements too.
// Taking care that you have it assigned
// correctly.
...
}
On called class:
public class MyFragment extends Fragment {
private MainActivity main; // Declare the activity var
...
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Assign the main activity var
main = (MainActivity) getActivity();
// Do what you want with the vars
main.str = "I changed your value!";
main.myEditText.setText("Wow I can modify the EditText too!");
...
return inflater.inflate(R.layout.my_fragment, container, false);
}
...
}
Note: Take care when using events (onClick, onChanged, etc) because you can be on a "fighting" situation where more than one assign a variable. The result will be that the variable sometimes does not will change or will return to the last value magically.
For more combinations use your creativity. :)
Yet another option (based on whether you want that if statement to be dynamically evaluated or not) is to use the C preprocessor, as described here.
I have used this before and I think in order to make sure credential persist and in a best secure way is
ConfigurationManager
classSecureString
classCryptography
namespace.This link will be of great help I hope : Click here
ah homework...
So wait, you need to deduct the balance of items in stock from the total number of those items that have been ordered? I have to tell you that sounds a bit backwards. Generally I think people do it the other way round. Deduct the total number of items ordered from the balance.
If you really need to do that though... Assuming that ITEM is unique in stock_bal...
SELECT s.ITEM, SUM(m.QTY) - s.QTY AS result
FROM stock_bal s
INNER JOIN master_table m ON m.ITEM = s.ITEM
GROUP BY s.ITEM, s.QTY
The AlexFTPS library used in the question seems to be dead (was not updated since 2011).
You can try to implement this without any external library. But unfortunately, neither the .NET Framework nor PowerShell have any explicit support for downloading all files in a directory (let only recursive file downloads).
You have to implement that yourself:
Tricky part is to identify files from subdirectories. There's no way to do that in a portable way with the .NET framework (FtpWebRequest
or WebClient
). The .NET framework unfortunately does not support the MLSD
command, which is the only portable way to retrieve directory listing with file attributes in FTP protocol. See also Checking if object on FTP server is file or directory.
Your options are:
ListDirectory
method (NLST
FTP command) and simply download all the "names" as files.LIST
command = ListDirectoryDetails
method) and try to parse a server-specific listing. Many FTP servers use *nix-style listing, where you identify a directory by the d
at the very beginning of the entry. But many servers use a different format. The following example uses this approach (assuming the *nix format)function DownloadFtpDirectory($url, $credentials, $localPath)
{
$listRequest = [Net.WebRequest]::Create($url)
$listRequest.Method = [System.Net.WebRequestMethods+Ftp]::ListDirectoryDetails
$listRequest.Credentials = $credentials
$lines = New-Object System.Collections.ArrayList
$listResponse = $listRequest.GetResponse()
$listStream = $listResponse.GetResponseStream()
$listReader = New-Object System.IO.StreamReader($listStream)
while (!$listReader.EndOfStream)
{
$line = $listReader.ReadLine()
$lines.Add($line) | Out-Null
}
$listReader.Dispose()
$listStream.Dispose()
$listResponse.Dispose()
foreach ($line in $lines)
{
$tokens = $line.Split(" ", 9, [StringSplitOptions]::RemoveEmptyEntries)
$name = $tokens[8]
$permissions = $tokens[0]
$localFilePath = Join-Path $localPath $name
$fileUrl = ($url + $name)
if ($permissions[0] -eq 'd')
{
if (!(Test-Path $localFilePath -PathType container))
{
Write-Host "Creating directory $localFilePath"
New-Item $localFilePath -Type directory | Out-Null
}
DownloadFtpDirectory ($fileUrl + "/") $credentials $localFilePath
}
else
{
Write-Host "Downloading $fileUrl to $localFilePath"
$downloadRequest = [Net.WebRequest]::Create($fileUrl)
$downloadRequest.Method = [System.Net.WebRequestMethods+Ftp]::DownloadFile
$downloadRequest.Credentials = $credentials
$downloadResponse = $downloadRequest.GetResponse()
$sourceStream = $downloadResponse.GetResponseStream()
$targetStream = [System.IO.File]::Create($localFilePath)
$buffer = New-Object byte[] 10240
while (($read = $sourceStream.Read($buffer, 0, $buffer.Length)) -gt 0)
{
$targetStream.Write($buffer, 0, $read);
}
$targetStream.Dispose()
$sourceStream.Dispose()
$downloadResponse.Dispose()
}
}
}
Use the function like:
$credentials = New-Object System.Net.NetworkCredential("user", "mypassword")
$url = "ftp://ftp.example.com/directory/to/download/"
DownloadFtpDirectory $url $credentials "C:\target\directory"
The code is translated from my C# example in C# Download all files and subdirectories through FTP.
If you want to avoid troubles with parsing the server-specific directory listing formats, use a 3rd party library that supports the MLSD
command and/or parsing various LIST
listing formats. And ideally with a support for downloading all files from a directory or even recursive downloads.
For example with WinSCP .NET assembly you can download whole directory with a single call to Session.GetFiles
:
# Load WinSCP .NET assembly
Add-Type -Path "WinSCPnet.dll"
# Setup session options
$sessionOptions = New-Object WinSCP.SessionOptions -Property @{
Protocol = [WinSCP.Protocol]::Ftp
HostName = "ftp.example.com"
UserName = "user"
Password = "mypassword"
}
$session = New-Object WinSCP.Session
try
{
# Connect
$session.Open($sessionOptions)
# Download files
$session.GetFiles("/directory/to/download/*", "C:\target\directory\*").Check()
}
finally
{
# Disconnect, clean up
$session.Dispose()
}
Internally, WinSCP uses the MLSD
command, if supported by the server. If not, it uses the LIST
command and supports dozens of different listing formats.
The Session.GetFiles
method is recursive by default.
(I'm the author of WinSCP)
Your command does not work because the redirection is performed by your shell which does not have the permission to write to /root/test.out
. The redirection of the output is not performed by sudo.
There are multiple solutions:
Run a shell with sudo and give the command to it by using the -c
option:
sudo sh -c 'ls -hal /root/ > /root/test.out'
Create a script with your commands and run that script with sudo:
#!/bin/sh
ls -hal /root/ > /root/test.out
Run sudo ls.sh
. See Steve Bennett's answer if you don't want to create a temporary file.
Launch a shell with sudo -s
then run your commands:
[nobody@so]$ sudo -s
[root@so]# ls -hal /root/ > /root/test.out
[root@so]# ^D
[nobody@so]$
Use sudo tee
(if you have to escape a lot when using the -c
option):
sudo ls -hal /root/ | sudo tee /root/test.out > /dev/null
The redirect to /dev/null
is needed to stop tee from outputting to the screen. To append instead of overwriting the output file
(>>
), use tee -a
or tee --append
(the last one is specific to GNU coreutils).
Thanks go to Jd, Adam J. Forster and Johnathan for the second, third and fourth solutions.
This is just a guess .. but
Because they are strings, they have some semantic value (the compiler doesn't get rid of them), therefore it makes sense for them to be used as docstrings. They actually become part of the AST, so extracting documentation becomes easier.
My two cents: came across the same error message in RHEL7.3 while running the openssl command with root CA certificate. The reason being, while downloading the certificate from AD server, Encoding was selected as DER instead of Base64. Once the proper version of encoding was selected for the new certificate download, error was resolved
Hope this helps for new users :-)
Try this code:
final String[] str = {"one","two","three","asdfgf"};
final RelativeLayout rl = (RelativeLayout) findViewById(R.id.rl);
final TextView[] tv = new TextView[10];
for (int i=0; i<str.length; i++)
{
tv[i] = new TextView(this);
RelativeLayout.LayoutParams params=new RelativeLayout.LayoutParams
((int)LayoutParams.WRAP_CONTENT,(int)LayoutParams.WRAP_CONTENT);
params.leftMargin = 50;
params.topMargin = i*50;
tv[i].setText(str[i]);
tv[i].setTextSize((float) 20);
tv[i].setPadding(20, 50, 20, 50);
tv[i].setLayoutParams(params);
rl.addView(tv[i]);
}
You can try something like this
IFNULL(NULLIF(X, '' ), 0)
Attribute X is assumed to be empty if it is an empty String, so after that you can declare as a zero instead of last value. In another case, it would remain its original value.
Anyway, just to give another way to do that.
The function Correlate of numpy works with 2 1D arrays that you want to correlate and returns one correlation value.
After becoming frustrated with the too many limitations of cut
, I wrote my own replacement, which I called cuts
for "cut on steroids".
cuts provides what is likely the most minimalist solution to this and many other related cut/paste problems.
One example, out of many, addressing this particular question:
$ cat text.txt
0 1 2 3
0 1 2 3 4
$ cuts 2 text.txt
2
2
cuts
supports:
paste
separately)and much more. None of which is provided by standard cut
.
See also: https://stackoverflow.com/a/24543231/1296044
Source and documentation (free software): http://arielf.github.io/cuts/
Error 127
means one of two things:
$PATH
, or in this case, the relative path is correct -- remember that the current working directory for a random terminal might not be the same for the IDE you're using. it might be better to just use an absolute path instead.file -L
on /bin/sh
(to get your default/native format) and on the compiler itself (to see what format it is).if the problem is (2), then you can solve it in a few diff ways:
Or File::Find
use File::Find;
finddepth(\&wanted, '/some/path/to/dir');
sub wanted { print };
It'll go through subdirectories if they exist.
A List
isn't a real thing in Java. It's an interface, a way of defining how an object is allowed to interact with other objects. As such, it can't ever be instantiated. An ArrayList
is an implementation of the List
interface, as is a linked list, and so on. Use those instead.
If you want to skip every other row and every other column, then you can do it with basic slicing:
In [49]: x=np.arange(16).reshape((4,4))
In [50]: x[1:4:2,1:4:2]
Out[50]:
array([[ 5, 7],
[13, 15]])
This returns a view, not a copy of your array.
In [51]: y=x[1:4:2,1:4:2]
In [52]: y[0,0]=100
In [53]: x # <---- Notice x[1,1] has changed
Out[53]:
array([[ 0, 1, 2, 3],
[ 4, 100, 6, 7],
[ 8, 9, 10, 11],
[ 12, 13, 14, 15]])
while z=x[(1,3),:][:,(1,3)]
uses advanced indexing and thus returns a copy:
In [58]: x=np.arange(16).reshape((4,4))
In [59]: z=x[(1,3),:][:,(1,3)]
In [60]: z
Out[60]:
array([[ 5, 7],
[13, 15]])
In [61]: z[0,0]=0
Note that x
is unchanged:
In [62]: x
Out[62]:
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15]])
If you wish to select arbitrary rows and columns, then you can't use basic slicing. You'll have to use advanced indexing, using something like x[rows,:][:,columns]
, where rows
and columns
are sequences. This of course is going to give you a copy, not a view, of your original array. This is as one should expect, since a numpy array uses contiguous memory (with constant strides), and there would be no way to generate a view with arbitrary rows and columns (since that would require non-constant strides).
Remove a list’s bullets and apply some light margin with a combination of two classes, .list-inline and .list-inline-item.
<ul class="list-inline">
<li class="list-inline-item"><a class="social-icon text-xs-center" target="_blank" href="#">FB</a></li>
<li class="list-inline-item"><a class="social-icon text-xs-center" target="_blank" href="#">G+</a></li>
<li class="list-inline-item"><a class="social-icon text-xs-center" target="_blank" href="#">T</a></li>
</ul>
You can get the functionality you want by sourcing the script instead of running it. eg:
$cat script cmd1 cmd2 $ . script $ at this point cmd1 and cmd2 have been run inside this shell
Primary Key: identify uniquely every row it can not be null. it can not be a duplicate.
Foreign Key: create relationship between two tables. can be null. can be a duplicate
Here is my solution for that:
EDIT - changed code a little bit
public static <E> Iterable<E> concat(final Iterable<? extends E> list1, Iterable<? extends E> list2)
{
return new Iterable<E>()
{
public Iterator<E> iterator()
{
return new Iterator<E>()
{
protected Iterator<? extends E> listIterator = list1.iterator();
protected Boolean checkedHasNext;
protected E nextValue;
private boolean startTheSecond;
public void theNext()
{
if (listIterator.hasNext())
{
checkedHasNext = true;
nextValue = listIterator.next();
}
else if (startTheSecond)
checkedHasNext = false;
else
{
startTheSecond = true;
listIterator = list2.iterator();
theNext();
}
}
public boolean hasNext()
{
if (checkedHasNext == null)
theNext();
return checkedHasNext;
}
public E next()
{
if (!hasNext())
throw new NoSuchElementException();
checkedHasNext = null;
return nextValue;
}
public void remove()
{
listIterator.remove();
}
};
}
};
}
Please "include" both Controller and the module(s) where the controller and the functions called in the Controller are.
module(theModule);
This worked for me.
.carousel-item {
height: 500px;
}
.item, img{
position: absolute;
object-fit:cover;
height: 100% !important;
width: 100% !important;
/*min-height: 500px;*/
}
To create/change a root password in a running container
docker exec -itu root {containerName} passwd
Here is example how you can do localization without some extra library.
jQuery(function($) {_x000D_
$('input.datetimepicker').datepicker({_x000D_
duration: '',_x000D_
changeMonth: false,_x000D_
changeYear: false,_x000D_
yearRange: '2010:2020',_x000D_
showTime: false,_x000D_
time24h: true_x000D_
});_x000D_
_x000D_
$.datepicker.regional['cs'] = {_x000D_
closeText: 'Zavrít',_x000D_
prevText: '<Dríve',_x000D_
nextText: 'Pozdeji>',_x000D_
currentText: 'Nyní',_x000D_
monthNames: ['leden', 'únor', 'brezen', 'duben', 'kveten', 'cerven', 'cervenec', 'srpen',_x000D_
'zárí', 'ríjen', 'listopad', 'prosinec'_x000D_
],_x000D_
monthNamesShort: ['led', 'úno', 'bre', 'dub', 'kve', 'cer', 'cvc', 'srp', 'zár', 'ríj', 'lis', 'pro'],_x000D_
dayNames: ['nedele', 'pondelí', 'úterý', 'streda', 'ctvrtek', 'pátek', 'sobota'],_x000D_
dayNamesShort: ['ne', 'po', 'út', 'st', 'ct', 'pá', 'so'],_x000D_
dayNamesMin: ['ne', 'po', 'út', 'st', 'ct', 'pá', 'so'],_x000D_
weekHeader: 'Týd',_x000D_
dateFormat: 'dd/mm/yy',_x000D_
firstDay: 1,_x000D_
isRTL: false,_x000D_
showMonthAfterYear: false,_x000D_
yearSuffix: ''_x000D_
};_x000D_
_x000D_
$.datepicker.setDefaults($.datepicker.regional['cs']);_x000D_
});
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<link data-require="jqueryui@*" data-semver="1.10.0" rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.10.0/css/smoothness/jquery-ui-1.10.0.custom.min.css" />_x000D_
<script data-require="jqueryui@*" data-semver="1.10.0" src="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.10.0/jquery-ui.js"></script>_x000D_
<script src="datepicker-cs.js"></script>_x000D_
<script type="text/javascript">_x000D_
$(document).ready(function() {_x000D_
console.log("test");_x000D_
$("#test").datepicker({_x000D_
dateFormat: "dd.m.yy",_x000D_
minDate: 0,_x000D_
showOtherMonths: true,_x000D_
firstDay: 1_x000D_
});_x000D_
});_x000D_
</script>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<h1>Here is your datepicker</h1>_x000D_
<input id="test" type="text" />_x000D_
</body>_x000D_
</html>
_x000D_
I used the below code to disable BT when my app launches and works fine. Not sure if this the correct way to implement this as google recommends not using "bluetooth.disable();" without explicit user action to turn off Bluetooth.
BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();
bluetooth.disable();
I only used the below permission.
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
The command select username from all_users;
requires less privileges
To prevent Dialog box from closing when clicked and it should only close when the internet is available
I am trying to do the same thing, as I don't want the dialog box to be closed until and unless the internet is connected.
Here is my code:
AlertDialog.Builder builder=new AlertDialog.Builder(MainActivity.this); builder.setTitle("Internet Not Connected");
if(ifConnected()){
Toast.makeText(this, "Connected or not", Toast.LENGTH_LONG).show();
}
else{
builder.setPositiveButton("Retry", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
if(!ifConnected())
{
builder.show();
}
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
finish();
}
});
builder.show();
}
And here is my Connectivity manager code:
private boolean ifConnected()
{
ConnectivityManager connectivityManager= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo=connectivityManager.getActiveNetworkInfo();
return networkInfo!=null && networkInfo.isConnected();
}
If someone is facing issue using texttocolumns function in UFT. Please try using below function.
myxl.Workbooks.Open myexcel.xls
myxl.Application.Visible = false `enter code here`
set mysheet = myxl.ActiveWorkbook.Worksheets(1)
Set objRange = myxl.Range("A1").EntireColumn
Set objRange2 = mysheet.Range("A1")
objRange.TextToColumns objRange2,1,1, , , , true
Here we are using coma(,) as delimiter.
As you've discovered, you can't do that. You can do:
libtest_LIBS =
...
if HAVE_CLIENT
libtest_LIBS += libclient.la
endif
if HAVE_SERVER
libtest_LIBS += libserver.la
endif
Edge case here but I tried (almost) all of the above answers above on VirtualBox and nothing was doing it but then closing not only the VirtualBoxVM but good ole VirtualBox itself and restarting the program itself did the trick without 0 complaint.
Hope that can help ~0.1% of queriers : )
This solution supports tab, backspace, enter, minus in intuitive way
<input type=text onkeypress="return /^-?[0-9]*$/.test(this.value+event.key)">
_x000D_
however it not allow to change already typed number to minus and not handle copy-paste case.
As alternative you can use solution based on R. Yaghoobi answer which allow to put minus and handle copy-paste case, but it delete whole number when user type forbidden character
<input type=text oninput="this.value= ['','-'].includes(this.value) ? this.value : this.value|0">
_x000D_
I use a way that may look stupid but it works for me. I simply concat the columns I want to compare and use NOT IN:
SELECT *
FROM table1 t1
WHERE CONCAT(t1.first_name,t1.last_name) NOT IN (SELECT CONCAT(t2.first_name,t2.last_name) FROM table2 t2)
Use the following code to capture picture using your mobile camera. If you are using android having version higher than Lolipop, You should add the permission request also.
private void cameraIntent()
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
}
@override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
}
}
I know this is an old question, but I had this problem recently and none of the answers helped me. However, Corral's comment on Ryan Atkinson's answer did tip me off to the problem.
I had all my compiled class files in target/classes
, which are not packages in my case. I was trying to package it with jar cvfe App.jar target/classes App
, from the root directory of my project, as my App class was in the default unnamed package.
This doesn't work, as the newly created App.jar
will have the class App.class
in the directory target/classes
. If you try to run this jar with java -jar App.jar
, it will complain that it cannot find the App
class. This is because the packages inside App.jar
don't match the actual packages in the project.
This could be solved by creating the jar directly from the target/classes
directory, using jar cvfe App.jar . App
. This is rather cumbersome in my opinion.
The simple solution is to list the folders you want to add with the -C
option instead of using the default way of listing folders. So, in my case, the correct command is java cvfe App.jar App -C target/classes .
. This will directly add all files in the target/classes
directory to the root of App.jar
, thus solving the problem.
With the following small function, digging into a tree-shaped dictionary becomes quite easy:
def dig(tree, path):
for key in path.split("."):
if isinstance(tree, dict) and tree.get(key):
tree = tree[key]
else:
return None
return tree
Now, dig(mydict, "Apple.Mexican")
returns 10
, while dig(mydict, "Grape")
yields the subtree {'Arabian':'25','Indian':'20'}
. If a key is not contained in the dictionary, dig
returns None
.
Note that you can easily change (or even parameterize) the separator char from '.' to '/', '|' etc.
Super late here and I still couldn't uninstall using sudo
as the other answers suggest. What did it for me was checking where cordova
was installed by running
which cordova
it will output something like this
/usr/local/bin/
then removing by
rm -rf /usr/local/bin/cordova
I too got the same error, problem in my case is I included the column name in GROUP BY
clause and it caused this error. So removed the column from GROUP BY
clause and it worked!!!
When running in a CI script, you will have trouble with imperative commands as create raises an error if the resource already exists.
What you can do is applying (declarative pattern) the output of your imperative command, by using --dry-run=true
and -o yaml
options:
kubectl create whatever --dry-run=true -o yaml | kubectl apply -f -
The command above will not raise an error if the resource already exists (and will update the resource if needed).
This is very useful in some cases where you cannot use the declarative pattern (for instance when creating a docker-registry secret).
I recently ran into this error on Windows 10. It turned out that windows was looking for .dll files necessary for my project and couldn't find them because it looks for them in the system path, PATH, rather than the CLASSPATH or -Djava.library.path
From the docs
Safety check 1
A designated initializer must ensure that all of the properties introduced by its class are initialized before it delegates up to a superclass initializer.
Why do we need a safety check like this?
To answer this lets go though the initialization process in swift.
Two-Phase Initialization
Class initialization in Swift is a two-phase process. In the first phase, each stored property is assigned an initial value by the class that introduced it. Once the initial state for every stored property has been determined, the second phase begins, and each class is given the opportunity to customize its stored properties further before the new instance is considered ready for use.
The use of a two-phase initialization process makes initialization safe, while still giving complete flexibility to each class in a class hierarchy. Two-phase initialization prevents property values from being accessed before they are initialized, and prevents property values from being set to a different value by another initializer unexpectedly.
So, to make sure the two step initialization process is done as defined above, there are four safety checks, one of them is,
Safety check 1
A designated initializer must ensure that all of the properties introduced by its class are initialized before it delegates up to a superclass initializer.
Now, the two phase initialization never talks about order, but this safety check, introduces super.init
to be ordered, after the initialization of all the properties.
Safety check 1 might seem irrelevant as, Two-phase initialization prevents property values from being accessed before they are initialized can be satisfied, without this safety check 1.
Like in this sample
class Shape {
var name: String
var sides : Int
init(sides:Int, named: String) {
self.sides = sides
self.name = named
}
}
class Triangle: Shape {
var hypotenuse: Int
init(hypotenuse:Int) {
super.init(sides: 3, named: "Triangle")
self.hypotenuse = hypotenuse
}
}
Triangle.init
has initialized, every property before being used. So Safety check 1 seems irrelevant,
But then there could be another scenario, a little bit complex,
class Shape {
var name: String
var sides : Int
init(sides:Int, named: String) {
self.sides = sides
self.name = named
printShapeDescription()
}
func printShapeDescription() {
print("Shape Name :\(self.name)")
print("Sides :\(self.sides)")
}
}
class Triangle: Shape {
var hypotenuse: Int
init(hypotenuse:Int) {
self.hypotenuse = hypotenuse
super.init(sides: 3, named: "Triangle")
}
override func printShapeDescription() {
super.printShapeDescription()
print("Hypotenuse :\(self.hypotenuse)")
}
}
let triangle = Triangle(hypotenuse: 12)
Output :
Shape Name :Triangle
Sides :3
Hypotenuse :12
Here if we had called the super.init
before setting the hypotenuse
, the super.init
call would then have called the printShapeDescription()
and since that has been overridden it would first fallback to Triangle class implementation of printShapeDescription()
. The printShapeDescription()
of Triangle class access the hypotenuse
a non optional property that still has not been initialised. And this is not allowed as Two-phase initialization prevents property values from being accessed before they are initialized
So make sure the Two phase initialization is done as defined, there needs to be a specific order of calling super.init
, and that is, after initializing all the properties introduced by self
class, thus we need a Safety check 1
The instruction has been tested on Mac OSx Catalina.
After installing Sublime Text 3
, install Package Control
through Tools > Package Control
.
Use the following instructions to install package
or theme
:
I've been given to understand that Python is an interpreted language...
This popular meme is incorrect, or, rather, constructed upon a misunderstanding of (natural) language levels: a similar mistake would be to say "the Bible is a hardcover book". Let me explain that simile...
"The Bible" is "a book" in the sense of being a class of (actual, physical objects identified as) books; the books identified as "copies of the Bible" are supposed to have something fundamental in common (the contents, although even those can be in different languages, with different acceptable translations, levels of footnotes and other annotations) -- however, those books are perfectly well allowed to differ in a myriad of aspects that are not considered fundamental -- kind of binding, color of binding, font(s) used in the printing, illustrations if any, wide writable margins or not, numbers and kinds of builtin bookmarks, and so on, and so forth.
It's quite possible that a typical printing of the Bible would indeed be in hardcover binding -- after all, it's a book that's typically meant to be read over and over, bookmarked at several places, thumbed through looking for given chapter-and-verse pointers, etc, etc, and a good hardcover binding can make a given copy last longer under such use. However, these are mundane (practical) issues that cannot be used to determine whether a given actual book object is a copy of the Bible or not: paperback printings are perfectly possible!
Similarly, Python is "a language" in the sense of defining a class of language implementations which must all be similar in some fundamental respects (syntax, most semantics except those parts of those where they're explicitly allowed to differ) but are fully allowed to differ in just about every "implementation" detail -- including how they deal with the source files they're given, whether they compile the sources to some lower level forms (and, if so, which form -- and whether they save such compiled forms, to disk or elsewhere), how they execute said forms, and so forth.
The classical implementation, CPython, is often called just "Python" for short -- but it's just one of several production-quality implementations, side by side with Microsoft's IronPython (which compiles to CLR codes, i.e., ".NET"), Jython (which compiles to JVM codes), PyPy (which is written in Python itself and can compile to a huge variety of "back-end" forms including "just-in-time" generated machine language). They're all Python (=="implementations of the Python language") just like many superficially different book objects can all be Bibles (=="copies of The Bible").
If you're interested in CPython specifically: it compiles the source files into a Python-specific lower-level form (known as "bytecode"), does so automatically when needed (when there is no bytecode file corresponding to a source file, or the bytecode file is older than the source or compiled by a different Python version), usually saves the bytecode files to disk (to avoid recompiling them in the future). OTOH IronPython will typically compile to CLR codes (saving them to disk or not, depending) and Jython to JVM codes (saving them to disk or not -- it will use the .class
extension if it does save them).
These lower level forms are then executed by appropriate "virtual machines" also known as "interpreters" -- the CPython VM, the .Net runtime, the Java VM (aka JVM), as appropriate.
So, in this sense (what do typical implementations do), Python is an "interpreted language" if and only if C# and Java are: all of them have a typical implementation strategy of producing bytecode first, then executing it via a VM/interpreter.
More likely the focus is on how "heavy", slow, and high-ceremony the compilation process is. CPython is designed to compile as fast as possible, as lightweight as possible, with as little ceremony as feasible -- the compiler does very little error checking and optimization, so it can run fast and in small amounts of memory, which in turns lets it be run automatically and transparently whenever needed, without the user even needing to be aware that there is a compilation going on, most of the time. Java and C# typically accept more work during compilation (and therefore don't perform automatic compilation) in order to check errors more thoroughly and perform more optimizations. It's a continuum of gray scales, not a black or white situation, and it would be utterly arbitrary to put a threshold at some given level and say that only above that level you call it "compilation"!-)
As per the comment by drris, if IsBodyHtml
is set to true then a standard newline could potentially be ignored by design, I know you mention avoiding HTML but try using <br />
instead, even if just to see if this 'solves' the problem - then you can rule out by what you know:
var message = new System.Net.Mail.MailMessage();
message.Body = "First Line <br /> second line";
You may also just try setting IsBodyHtml
to false
and determining if newlines work in that instance, although, unless you set it to true
explicitly I'm pretty sure it defaults to false
anyway.
Also as a side note, avoiding HTML in emails is not necessarily any aid in getting the message through spam filters, AFAIK - if anything, the most you do by this is ensure cross-mail-client compatibility in terms of layout. To 'play nice' with spam filters, a number of other things ought to be taken into account; even so much as the subject and content of the mail, who the mail is sent from and where and do they match et cetera. An email simply won't be discriminated against because it is marked up with HTML.
You can do it like... Just give the proper path of your json file...
<!doctype html>
<html>
<head>
<script type="text/javascript" src="abc.json"></script>
<script type="text/javascript" >
function load() {
var mydata = JSON.parse(data);
alert(mydata.length);
var div = document.getElementById('data');
for(var i = 0;i < mydata.length; i++)
{
div.innerHTML = div.innerHTML + "<p class='inner' id="+i+">"+ mydata[i].name +"</p>" + "<br>";
}
}
</script>
</head>
<body onload="load()">
<div id= "data">
</div>
</body>
</html>
Simply getting the data and appending it to a div... Initially printing the length in alert.
Here is my Json file: abc.json
data = '[{"name" : "Riyaz"},{"name" : "Javed"},{"name" : "Arun"},{"name" : "Sunil"},{"name" : "Rahul"},{"name" : "Anita"}]';
After my previous answer disaster, I'm going to try something else.
List<Model> usrList =
(list.Where(n => n.application == "applicationame").ToList());
usrList.ForEach(n => n.users.RemoveAll(n => n.surname != "surname"));
Remove the *
from your query and use individual column names, like this:
SELECT SOME_OTHER_COLUMN, CONCAT(FIRSTNAME, ',', LASTNAME) AS FIRSTNAME FROM `customer`;
Using *
means, in your results you want all the columns of the table. In your case *
will also include FIRSTNAME
. You are then concatenating some columns and using alias of FIRSTNAME
. This creates 2 columns with same name.
Also be sure to check out \H, which toggles HTML output on/off. Not necessarily easy to read at the console, but interesting for dumping into a file (see \o) or pasting into an editor/browser window for viewing, especially with multiple rows of relatively complex data.
Please check you are using //
not \\
by-mistake , like below
Wrong:"http:\\stackoverflow.com"
Right:"http://stackoverflow.com"
In Xcode 8 beta 4 does not work...
Use:
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
print("Are we there yet?")
}
for async two ways:
DispatchQueue.main.async {
print("Async1")
}
DispatchQueue.main.async( execute: {
print("Async2")
})
Using an empty string is perfectly fine and actually much safer than simply using $_SERVER['PHP_SELF']
.
When using $_SERVER['PHP_SELF']
it is very easy to inject malicious data by simply appending /<script>...
after the whatever.php
part of the URL so you should not use this method and stop using any PHP tutorial that suggests it.
To me, the problem is readability.
A while statement with a true condition tells you nothing about the loop. It makes the job of understanding it much more difficult.
What would be easier to understand out of these two snippets?
do {
// Imagine a nice chunk of code here
} while(true);
do {
// Imagine a nice chunk of code here
} while(price < priceAllowedForDiscount);
JAR File Manifest Attributes for Security
The JAR file manifest contains information about the contents of the JAR file, including security and configuration information.
Add the attributes to the manifest before the JAR file is signed.
See Modifying a Manifest File in the Java Tutorial for information on adding attributes to the JAR manifest file.
Permissions Attribute
The Permissions attribute is used to verify that the permissions level requested by the RIA when it runs matches the permissions level that was set when the JAR file was created.
Use this attribute to help prevent someone from re-deploying an application that is signed with your certificate and running it at a different privilege level. Set this attribute to one of the following values:
sandbox - runs in the security sandbox and does not require additional permissions.
all-permissions - requires access to the user's system resources.
Changes to Security Slider:
The following changes to Security Slider were included in this release(7u51):
For more information, see Java Control Panel documentation.
sample MANIFEST.MF
Manifest-Version: 1.0
Ant-Version: Apache Ant 1.8.3
Created-By: 1.7.0_51-b13 (Oracle Corporation)
Trusted-Only: true
Class-Path: lib/plugin.jar
Permissions: sandbox
Codebase: http://myweb.de http://www.myweb.de
Application-Name: summary-applet
Also note that the SPOOL
output is driven by a few SQLPlus settings:
SET LINESIZE nn
- maximum line width; if the output is longer it will wrap to display the contents of each result row.
SET TRIMSPOOL OFF|ON
- if set OFF
(the default), every output line will be padded to LINESIZE
. If set ON
, every output line will be trimmed.
SET PAGESIZE nn
- number of lines to output for each repetition of the header. If set to zero, no header is output; just the detail.
Those are the biggies, but there are some others to consider if you just want the output without all the SQLPlus chatter.
The font sizes in your question are an example of what ratio each header should be in comparison to each other, rather than what size they should be themselves (in pixels).
So in response to your question "Is there a 'best practice' for these for mobile phones? - say iphone screen size?", yes there probably is - but you might find what someone says is "best practice" does not work for your layout.
However, to help get you on the right track, this article about building responsive layouts provides a good example of how to calculate the base font-size
in pixels in relation to device screen sizes.
The suggested font-sizes for screen resolutions suggested from that article are as follows:
@media (min-width: 858px) {
html {
font-size: 12px;
}
}
@media (min-width: 780px) {
html {
font-size: 11px;
}
}
@media (min-width: 702px) {
html {
font-size: 10px;
}
}
@media (min-width: 724px) {
html {
font-size: 9px;
}
}
@media (max-width: 623px) {
html {
font-size: 8px;
}
}
If you want to force Keras to use CPU
import os
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID" # see issue #152
os.environ["CUDA_VISIBLE_DEVICES"] = ""
before Keras / Tensorflow is imported.
Run your script as
$ CUDA_VISIBLE_DEVICES="" ./your_keras_code.py
See also
When you call "https://darkorbit.com/" your server figures that it's missing "www" so it redirects the call to "http://www.darkorbit.com/" and then to "https://www.darkorbit.com/", your WebView call is blocked at the first redirection as it's a "http" call. You can call "https://www.darkorbit.com/" instead and it will solve the issue.
There is no "isContentViewSet" method. You may put some dummy requestWindowFeature call into try/catch block before setContentView like this:
try { requestWindowFeature(Window.FEATURE_CONTEXT_MENU); setContentView(...) } catch (AndroidRuntimeException e) { // do smth or nothing }
If content view was already set, requestWindowFeature will throw an exception.
I'd just like to say I had a particular object that had variable attributes (it was basically mapping a table and I was changing the columns in the table, so the attributes in the object, reflecting the table would vary as well):
class obj {
protected $fields = array('field1','field2');
protected $field1 = array();
protected $field2 = array();
protected loadfields(){}
// This will load the $field1 and $field2 with rows of data for the column they describe
protected function clearFields($num){
foreach($fields as $field) {
unset($this->$field[$num]);
// This did not work the line below worked
unset($this->{$field}[$num]); // You have to resolve $field first using {}
}
}
}
The whole purpose of $fields
was just, so I don't have to look everywhere in the code when they're changed, I just look at the beginning of the class and change the list of attributes and the $fields array content to reflect the new attributes.
Replace Your onOptionsItemSelected
as:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case OK_MENU_ITEM:
startActivity(new Intent(DashboardActivity.this, SettingActivity.class));
break;
// You can handle other cases Here.
default:
super.onOptionsItemSelected(item);
}
}
Here, I want to navigate from DashboardActivity
to SettingActivity
.
I have installed python2.7 and python3.6
Open Command Line to ~/.bash_profile I find that #Setting PATH for Python 3.6 , So I change the path to PATH="/usr/local/Cellar/python/2.7.13/bin:${PATH}" , (please make sure your python2.7's path) ,then save. It works for me.
Another way of doing this is setting the collectionView.center.x
, like so:
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
if let
collectionView = collectionView,
layout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout
{
collectionView.center.x = view.center.x + layout.sectionInset.right / 2.0
}
}
In this case, only respecting the right inset which works for me.
Maybe it would be better if you would read your excel file from PHP, and then either save it to a DB or do some processing on it.
here an in-dept tutorial on how to read and write Excel data with PHP:
http://www.ibm.com/developerworks/opensource/library/os-phpexcel/index.html
Here is my solution for key phrases of the messages: “unable to find valid certification path” and “PKIX path building failed“.
These phrases are shown when a SSL certification file can not be found.
Open https://jcenter.bintray.com/ in your browse and export the certificate in cer format.
Put the certificate in Android Studio’s cert folder
{your-home-directory}/.AndroidStudio3.0/system/tasks/cacerts
Then all went well.
I've finally solve the problem!!
@RobG was right about the form
tag and table
tag. the form
tag should be placed outside the table. with that,
<td><input type="reset" id="configreset" value="Reset"></td>
works without the need of jquery or anything else. simple click on the button and tadaa~ the whole form is reset ;) brilliant!
This seems a bit superfluous, but this is a methodology that I have used a few times, especially where I am integrating with xml or some such.
#model
class Profession
def self.pro_enum
{:BAKER => 0,
:MANAGER => 1,
:FIREMAN => 2,
:DEV => 3,
:VAL => ["BAKER", "MANAGER", "FIREMAN", "DEV"]
}
end
end
Profession.pro_enum[:DEV] #=>3
Profession.pro_enum[:VAL][1] #=>MANAGER
This gives me the rigor of a c# enum and it is tied to the model.
My current choice is Razor. It is very clean and easy to read and keeps the view pages very easy to maintain. There is also intellisense support which is really great. ALos, when used with web helpers it is really powerful too.
To provide a simple sample:
@Model namespace.model
<!Doctype html>
<html>
<head>
<title>Test Razor</title>
</head>
<body>
<ul class="mainList">
@foreach(var x in ViewData.model)
{
<li>@x.PropertyName</li>
}
</ul>
</body>
And there you have it. That is very clean and easy to read. Granted, that's a simple example but even on complex pages and forms it is still very easy to read and understand.
As for the cons? Well so far (I'm new to this) when using some of the helpers for forms there is a lack of support for adding a CSS class reference which is a little annoying.
Thanks Nathj07
You should try using isinstance()
if isinstance(object, list):
## DO what you want
In your case
if isinstance(tmpDict[key], list):
## DO SOMETHING
To elaborate:
x = [1,2,3]
if type(x) == list():
print "This wont work"
if type(x) == list: ## one of the way to see if it's list
print "this will work"
if type(x) == type(list()):
print "lets see if this works"
if isinstance(x, list): ## most preferred way to check if it's list
print "This should work just fine"
The difference between isinstance()
and type()
though both seems to do the same job is that isinstance()
checks for subclasses in addition, while type()
doesn’t.
I will show you some example
First I extract the text data from the data frame (twitter_df
) to process further as following
from nltk.tokenize import word_tokenize
tweetText = twitter_df['text']
Then to tokenize I use the following method
from nltk.tokenize import word_tokenize
tweetText = tweetText.apply(word_tokenize)
Then, to remove stop words,
from nltk.corpus import stopwords
nltk.download('stopwords')
stop_words = set(stopwords.words('english'))
tweetText = tweetText.apply(lambda x:[word for word in x if word not in stop_words])
tweetText.head()
I Think this will help you
I'm not with computer,so I write a draft. You might be clear of what I say.
func main(){
const dir = "/etc/"
filesInfo, e := ioutil.ReadDir(dir)
var fileNames = make([]string, 0, 10)
for i,v:=range filesInfo{
if !v.IsDir() {
fileNames = append(fileNames, v.Name())
}
}
var fileNumber = len(fileNames)
var contents = make([]string, fileNumber, 10)
wg := sync.WaitGroup{}
wg.Add(fileNumber)
for i,_:=range content {
go func(i int){
defer wg.Done()
buf,e := ioutil.Readfile(fmt.Printf("%s/%s", dir, fileName[i]))
defer file.Close()
content[i] = string(buf)
}(i)
}
wg.Wait()
}
Thanks, but that was not the solution. I found it out why it wasn't working for me.
Since I'd done a declaration:
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
I thought I would refer to root directory of the project when beans.xml file was there. Then I put the configuration file to src/main/resources and changed initialization to:
ApplicationContext context = new ClassPathXmlApplicationContext("src/main/resources/beans.xml");
it still was an IO Exception.
Then the file was left in src/main/resources/ but I changed declaration to:
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
and it solved the problem - maybe it will be helpful for someone.
thanks and cheers!
Edit:
Since I get many people thumbs up for the solution and had had first experience with Spring as student few years ago, I feel desire to explain shortly why it works.
When the project is being compiled and packaged, all the files and subdirs from 'src/main/java' in the project goes to the root directory of the packaged jar (the artifact we want to create). The same rule applies to 'src/main/resources'.
This is a convention respected by many tools like maven or sbt in process of building project (note: as a default configuration!). When code (from the post) was in running mode, it couldn't find nothing like "src/main/resources/beans.xml" due to the fact, that beans.xml was in the root of jar (copied to /beans.xml in created jar/ear/war).
When using ClassPathXmlApplicationContext, the proper location declaration for beans xml definitions, in this case, was "/beans.xml", since this is path where it belongs in jar and later on in classpath.
It can be verified by unpacking a jar with an archiver (i.e. rar) and see its content with the directories structure.
I would recommend reading articles about classpath as supplementary.
First, note that restarting httpd is not necessary for .htaccess files. .htaccess files are specifically for people who don't have root - ie, don't have access to the httpd server config file, and can't restart the server. As you're able to restart the server, you don't need .htaccess files and can use the main server config directly.
Secondly, if .htaccess files are being ignored, you need to check to see that AllowOverride is set correctly. See http://httpd.apache.org/docs/2.4/mod/core.html#allowoverride for details. You need to also ensure that it is set in the correct scope - ie, in the right block in your configuration. Be sure you're NOT editing the one in the block, for example.
Third, if you want to ensure that a .htaccess file is in fact being read, put garbage in it. An invalid line, such as "INVALID LINE HERE", in your .htaccess file, will result in a 500 Server Error when you point your browser at the directory containing that file. If it doesn't, then you don't have AllowOverride configured correctly.
I was getting the below as well trying to get out to github.com as our proxy re-writes the HTTPS connection with their self-signed cert:
no peer certificate available No client certificate CA names sent
In my output there was also:
Protocol : TLSv1.3
I added -tls1_2
and it worked fine and now I can see which CA it is using on the outgoing request. e.g.:
openssl s_client -connect github.com:443 -tls1_2
If you need to retrieve a URL query from outside a component:
import router from 'next/router'
console.log(router.query)
index.php
<body>
...
<input id="Div7" name="Txt_Nombre" maxlenght="100px" placeholder="Nombre" />
<input id="Div8" name="Txt_Correo" maxlenght="100px" placeholder="Correo" />
<textarea id="Div9" name="Txt_Pregunta" placeholder="Pregunta" /></textarea>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$(".Txt_Enviar").click(function() { EnviarCorreo(); });
});
function EnviarCorreo()
{
jQuery.ajax({
type: "POST",
url: 'servicios.php',
data: {functionname: 'enviaCorreo', arguments: [$(".Txt_Nombre").val(), $(".Txt_Correo").val(), $(".Txt_Pregunta").val()]},
success:function(data) {
alert(data);
}
});
}
</script>
servicios.php
<?php
include ("correo.php");
$nombre = $_POST["Txt_Nombre"];
$correo = $_POST["Txt_Corro"];
$pregunta = $_POST["Txt_Pregunta"];
switch($_POST["functionname"]){
case 'enviaCorreo':
EnviaCorreoDesdeWeb($nombre, $correo, $pregunta);
break;
}
?>
correo.php
<?php
function EnviaCorreoDesdeWeb($nombre, $correo, $pregunta)
{
...
}
?>
You can do it like this:
var myApp = angular.module('myApp', [])
.controller('Ctrl', ['$scope', function($scope) {
$scope.aaa = 3432
}])
.directive('test', function () {
return {
link: function (scope, elm, attr) {
var look = elm.children('#findme').addClass("addedclass");
console.log(look);
}
};
});
<div ng-app="myApp" ng-controller="Ctrl">
<div test>TEST Div
<div id="findme">{{aaa}}</div>
</div>
</div>
First of all we will need serializeObject();
$.fn.serializeObject = function () {
var o = {};
var a = this.serializeArray();
$.each(a, function () {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
then you make a basic post and get response
$.post("/Education/StudentSave", $("#frmNewStudent").serializeObject(), function (data) {
if(data){
//do true
}
else
{
//do false
}
});
Using a (very) commonly used package is prefered:
import matplotlib.pyplot as plt
im = plt.imread('image.png')
np.isnan
can be applied to NumPy arrays of native dtype (such as np.float64):
In [99]: np.isnan(np.array([np.nan, 0], dtype=np.float64))
Out[99]: array([ True, False], dtype=bool)
but raises TypeError when applied to object arrays:
In [96]: np.isnan(np.array([np.nan, 0], dtype=object))
TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
Since you have Pandas, you could use pd.isnull
instead -- it can accept NumPy arrays of object or native dtypes:
In [97]: pd.isnull(np.array([np.nan, 0], dtype=float))
Out[97]: array([ True, False], dtype=bool)
In [98]: pd.isnull(np.array([np.nan, 0], dtype=object))
Out[98]: array([ True, False], dtype=bool)
Note that None
is also considered a null value in object arrays.
I was having the same problem. None of the above solutions worked for me. The key challenge was that I didn't have the root access. So, I first download the source of libffi. Then I compiled it with usual commands:
./configure --prefix=desired_installation_path_to_libffi
make
Then I recompiled python using
./configure --prefix=/home/user123/Softwares/Python/installation3/ LDFLAGS='-L/home/user123/Softwares/library/libffi/installation/lib64'
make
make install
In my case, 'home/user123/Softwares/library/libffi/installation/lib64' is path to LIBFFI installation directory where libffi.so is located. And, /home/user123/Softwares/Python/installation3/ is path to Python installation directory. Modify them as per your case.
Here is a smart and fast way to do it for numbers up to and around 10**16 in pure Python 3.6,
from itertools import compress
def primes(n):
""" Returns a list of primes < n for n > 2 """
sieve = bytearray([True]) * (n//2)
for i in range(3,int(n**0.5)+1,2):
if sieve[i//2]:
sieve[i*i//2::i] = bytearray((n-i*i-1)//(2*i)+1)
return [2,*compress(range(3,n,2), sieve[1:])]
def factorization(n):
""" Returns a list of the prime factorization of n """
pf = []
for p in primeslist:
if p*p > n : break
count = 0
while not n % p:
n //= p
count += 1
if count > 0: pf.append((p, count))
if n > 1: pf.append((n, 1))
return pf
def divisors(n):
""" Returns an unsorted list of the divisors of n """
divs = [1]
for p, e in factorization(n):
divs += [x*p**k for k in range(1,e+1) for x in divs]
return divs
n = 600851475143
primeslist = primes(int(n**0.5)+1)
print(divisors(n))
Your method (placing script before the closing body tag)
<script>
myFunction()
</script>
</body>
</html>
is a reliable way to support old and new browsers.
Change the appcompat version in your build.gradle file back to 22.2.1 (or whatever you were using before).
Once upon a time, the int datatype was pegged to the register size of the machine targeted by the compiler. So, for example, a compiler for a 16-bit system would use a 16-bit integer.
However, we thankfully don't see much 16-bit any more, and when 64-bit started to get popular people were more concerned with making it compatible with older software and 32-bit had been around so long that for most compilers an int is just assumed to be 32 bits.
Not a queue example, but extremely simple :)
class MyHouse {
private boolean pizzaArrived = false;
public void eatPizza(){
synchronized(this){
while(!pizzaArrived){
wait();
}
}
System.out.println("yumyum..");
}
public void pizzaGuy(){
synchronized(this){
this.pizzaArrived = true;
notifyAll();
}
}
}
Some important points:
1) NEVER do
if(!pizzaArrived){
wait();
}
Always use while(condition), because
while(!pizzaExists){ wait(); }
.2) You must hold the lock (synchronized) before invoking wait/nofity. Threads also have to acquire lock before waking.
3) Try to avoid acquiring any lock within your synchronized block and strive to not invoke alien methods (methods you don't know for sure what they are doing). If you have to, make sure to take measures to avoid deadlocks.
4) Be careful with notify(). Stick with notifyAll() until you know what you are doing.
5)Last, but not least, read Java Concurrency in Practice!
git pull
is really just a shorthand for git pull <remote> <branchname>
, in most cases it's equivalent to git pull origin master
. You will need to add another remote and pull explicitly from it. This page describes it in detail:
You would use the read.csv
function; for example:
dat = read.csv("spam.csv", header = TRUE)
You can also reference this tutorial for more details.
Note: make sure the .csv
file to read is in your working directory (using getwd()
) or specify the right path to file. If you want, you can set the current directory using setwd
.
sorry to dig this up, I just want to share my idea, the easy way for me is to rename composer.phar to composer.bat and put it into my PATH.
Try with: format(now(), "yyyy-MM-dd hh:mm:ss")
I've had the same problem and been working on it for hours. I've finally come up something that works.
Basically nothing I tried worked in every situation until I positioned a div to replicate the text of the first option over the select box and left the actual first option blank. I used {pointer-events:none;} to let users click through the div.
HTML
<div class='custom-select-container'>
<select>
<option></option>
<option>option 1</option>
<option>option 2</option>
</select>
<div class='custom-select'>
Select an option
</div>
<div>
CSS
.custom-select{position:absolute; left:28px; top:10px; z-index:1; display:block; pointer-events:none;}
If the background doesn't have to repeat, you can use the sprite technique (sliding-doors) where you put all the images with differing opacity into one (next to each other) and then just shift them around with background-position
.
Or you could declare the same partially transparent background image more than once, if your target browser supports multiple backgrounds (Firefox 3.6+, Safari 1.0+, Chrome 1.3+, Opera 10.5+, Internet Explorer 9+). The opacity of those multiple images should add up, the more backgrounds you define.
This process of combining transparencies is called Alpha Blending and calculated as (thanks @IainFraser):
a? = a1 + a2(1-a1)
where a
ranges between 0 and 1.
A perl oneliner would do: perl -i.bak -pe 's/[^[:ascii:]]//g' <your file>
-i
says that the file is going to be edited inplace, and the backup is going to be saved with extension .bak
.
The Problem: Github is not familiar with your repository from some reason.
The Error: prompted in git cli like the following:
remote: Repository not found. fatal: repository ‘https://github.com/MyOrganization/projectName.git/’ not found
The Solution : 2 Options
Github might not familiar with your credentials: - The first Option is to clone the project with the right credentials user:password
in case you forgot this Or generate ssh token and adjust this key in your Github. aka git push https://<userName>:<password>@github.com/Company/repositoryName.git
Repo Permissions Issue with some users - In my Use case, I solved this issue when I realized I don't have the right collaborator permissions on Github in my private repo. Users could clone the project but not perform any actions on origin. In order to solve this:
Go to Repository on Github -> Settings -> Collaborators & Teams -> Add Member/Maintainer your users -> Now they got the permission to commit and push
You can use extension methods to achive this.
public static ObjRemoverExtension {
public static void DeleteObj<T>(this T obj) where T: new()
{
obj = null;
}
}
And then you just import it in a desired source file and use on any object. GC will collect it. Like this:Car.DeleteObj()
EDIT Sorry didn't notice the method of class/all references part, but i'll leave it anyway.
"Server unable to read htaccess file" means just that. Make sure that the permissions on your .htaccess
file are world-readable.
Had a similar problem. Needed to append as many text inputs as the user wanted, to a form. The functionality of it using jQuery was the answer to the question:
<div id='inputdiv'>
<button id='mybutton'>add an input</button>
</div>
<script>
var thecounter=0; //declare and initialize the counter outside of the function
$('#mybutton').on('click', function(){
thecounter++;
$('#inputdiv').append('<input id="input'+thecounter+'" type="text/>);
});
</script>
Adding the count to each new input id resulted in unique ids which lets you get all the values using the jQuery serialize() function.
Left bit shifting to multiply by any power of two and right bit shifting to divide by any power of two.
For example, x = x * 2;
can also be written as x<<1
or x = x*8
can be written as x<<3
(since 2 to the power of 3 is 8). Similarly x = x / 2;
is x>>1
and so on.
Enter the image and give height:100%;width:auto
then just change the height of navbar itself to resize image. There is a really good example in codepen. https://codepen.io/bootstrapped/pen/KwYGwq
Some great answers here detailing how they both work.
Just adding one that answers the specific question asked:
When should I use
nextTick
and when should I usesetImmediate
?
setImmediate
.The Node.js Event Loop, Timers, and process.nextTick()
doc includes the following:
We recommend developers use
setImmediate()
in all cases because it's easier to reason about (and it leads to code that's compatible with a wider variety of environments, like browser JS.)
Earlier in the doc it warns that process.nextTick
can lead to...
some bad situations because it allows you to "starve" your I/O by making recursive
process.nextTick()
calls, which prevents the event loop from reaching the poll phase.
As it turns out, process.nextTick
can even starve Promises
:
Promise.resolve().then(() => { console.log('this happens LAST'); });
process.nextTick(() => {
console.log('all of these...');
process.nextTick(() => {
console.log('...happen before...');
process.nextTick(() => {
console.log('...the Promise ever...');
process.nextTick(() => {
console.log('...has a chance to resolve');
})
})
})
})
On the other hand, setImmediate
is "easier to reason about" and avoids these types of issues:
Promise.resolve().then(() => { console.log('this happens FIRST'); });
setImmediate(() => {
console.log('this happens LAST');
})
So unless there is a specific need for the unique behavior of process.nextTick
, the recommended approach is to "use setImmediate()
in all cases".
You have no width set and there is not content in the divs is one issue. The other is that the way html works... when all three of fixed, is that the hierarchy goes from bottom to top... so the content is on top of the header since they are both fixed... so in this case you need to declare a z-index on the header... but I wouldn't do that... leave that one relative so it can scroll normally.
Go mobile first on this... FIDDLE HERE
HTML
<header class="global-header">HEADER</header>
<section class="main-content">CONTENT</section>
<footer class="global-footer">FOOTER</footer>
CSS html, body { padding: 0; margin: 0; height: 100%; }
.global-header {
width: 100%;
float: left;
min-height: 5em;
background-color: red;
}
.main-content {
width: 100%;
float: left;
height: 50em;
background-color: yellow;
}
.global-footer {
width: 100%;
float: left;
min-height: 5em;
background-color: lightblue;
}
@media (min-width: 30em) {
.global-header {
position: fixed;
top: 0;
left: 0;
}
.main-content {
height: 100%;
margin-top: 5em; /* to offset header */
}
.global-footer {
position: fixed;
bottom: 0;
left: 0;
}
} /* ================== */
I think you must have named the file as nltk.py (or the folder consists of a file with that name) so change it to any other name and try executing it....
The only portable way to achieve consistency between rooms and tags and making sure rooms are never returned after they had been deleted is locking them with SELECT FOR UPDATE
.
However in some systems locking is a side effect of concurrency control, and you achieve the same results without specifying FOR UPDATE
explicitly.
To solve this problem, Thread 1 should
SELECT id FROM rooms FOR UPDATE
, thereby preventing Thread 2 from deleting fromrooms
until Thread 1 is done. Is that correct?
This depends on the concurrency control your database system is using.
MyISAM
in MySQL
(and several other old systems) does lock the whole table for the duration of a query.
In SQL Server
, SELECT
queries place shared locks on the records / pages / tables they have examined, while DML
queries place update locks (which later get promoted to exclusive or demoted to shared locks). Exclusive locks are incompatible with shared locks, so either SELECT
or DELETE
query will lock until another session commits.
In databases which use MVCC
(like Oracle
, PostgreSQL
, MySQL
with InnoDB
), a DML
query creates a copy of the record (in one or another way) and generally readers do not block writers and vice versa. For these databases, a SELECT FOR UPDATE
would come handy: it would lock either SELECT
or the DELETE
query until another session commits, just as SQL Server
does.
When should one use
REPEATABLE_READ
transaction isolation versusREAD_COMMITTED
withSELECT ... FOR UPDATE
?
Generally, REPEATABLE READ
does not forbid phantom rows (rows that appeared or disappeared in another transaction, rather than being modified)
In Oracle
and earlier PostgreSQL
versions, REPEATABLE READ
is actually a synonym for SERIALIZABLE
. Basically, this means that the transaction does not see changes made after it has started. So in this setup, the last Thread 1
query will return the room as if it has never been deleted (which may or may not be what you wanted). If you don't want to show the rooms after they have been deleted, you should lock the rows with SELECT FOR UPDATE
In InnoDB
, REPEATABLE READ
and SERIALIZABLE
are different things: readers in SERIALIZABLE
mode set next-key locks on the records they evaluate, effectively preventing the concurrent DML
on them. So you don't need a SELECT FOR UPDATE
in serializable mode, but do need them in REPEATABLE READ
or READ COMMITED
.
Note that the standard on isolation modes does prescribe that you don't see certain quirks in your queries but does not define how (with locking or with MVCC
or otherwise).
When I say "you don't need SELECT FOR UPDATE
" I really should have added "because of side effects of certain database engine implementation".
Use a negative match. (Also note that whitespace is significant, by default, inside a regex so don't space things out. Alternatively, use re.VERBOSE.)
for item in output:
matchObj = re.search("^(OK|\\.)", item)
if not matchObj:
print "got item " + item
Though there are other correct answers here (such as using classes), from an academic point of view it is of course possible to have multiple divs with the same ID, and it is possible to select them with jQuery.
When you use
jQuery("#elemid")
it selects only the first element with the given ID.
However, when you select by attribute (e.g. id in your case), it returns all matching elements, like so:
jQuery("[id=elemid]")
This of course works for selection on any attribute, and you could further refine your selection by specifying the tag in question (e.g. div in your case)
jQuery("div[id=elemid]")
Make sure that firefox must install on default place like ->(c:/Program Files (x86)/mozilla firefox OR c:/Program Files/mozilla firefox, note: at the time of firefox installation do not change the path so let it installing in default path) If firefox is installed on some other place then selenium show those error.
If you have set your firefox in Systems(Windows) environment variable then either remove it or update it with new firefox version path.
If you want to use Firefox in any other place then use below code:-
As FirefoxProfile is depricated we need to use FirefoxOptions as below:
New Code:
File pathBinary = new File("C:\\Program Files\\Mozilla Firefox\\firefox.exe");
FirefoxBinary firefoxBinary = new FirefoxBinary(pathBinary);
DesiredCapabilities desired = DesiredCapabilities.firefox();
FirefoxOptions options = new FirefoxOptions();
desired.setCapability(FirefoxOptions.FIREFOX_OPTIONS, options.setBinary(firefoxBinary));
The full working code of above code is as below:
System.setProperty("webdriver.gecko.driver","D:\\Workspace\\demoproject\\src\\lib\\geckodriver.exe");
File pathBinary = new File("C:\\Program Files\\Mozilla Firefox\\firefox.exe");
FirefoxBinary firefoxBinary = new FirefoxBinary(pathBinary);
DesiredCapabilities desired = DesiredCapabilities.firefox();
FirefoxOptions options = new FirefoxOptions();
desired.setCapability(FirefoxOptions.FIREFOX_OPTIONS, options.setBinary(firefoxBinary));
WebDriver driver = new FirefoxDriver(options);
driver.get("https://www.google.co.in/");
Download geckodriver for firefox from below URL:
https://github.com/mozilla/geckodriver/releases
Old Code which will work for old selenium jars versions
File pathBinary = new File("C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe");
FirefoxBinary firefoxBinary = new FirefoxBinary(pathBinary);
FirefoxProfile firefoxProfile = new FirefoxProfile();
WebDriver driver = new FirefoxDriver(firefoxBinary, firefoxProfile);
In Internet Explorer 9 (and 8), the console
object is only exposed when the developer tools are opened for a particular tab. If you hide the developer tools window for that tab, the console
object remains exposed for each page you navigate to. If you open a new tab, you must also open the developer tools for that tab in order for the console
object to be exposed.
The console
object is not part of any standard and is an extension to the Document Object Model. Like other DOM objects, it is considered a host object and is not required to inherit from Object
, nor its methods from Function
, like native ECMAScript functions and objects do. This is the reason apply
and call
are undefined on those methods. In IE 9, most DOM objects were improved to inherit from native ECMAScript types. As the developer tools are considered an extension to IE (albeit, a built-in extension), they clearly didn't receive the same improvements as the rest of the DOM.
For what it's worth, you can still use some Function.prototype
methods on console
methods with a little bind()
magic:
var log = Function.prototype.bind.call(console.log, console);
log.apply(console, ["this", "is", "a", "test"]);
//-> "thisisatest"
Check if you have the linebreak-style
rule configure as below either in your .eslintrc or in source code:
/*eslint linebreak-style: ["error", "unix"]*/
Since you're working on Windows, you may want to use this rule instead:
/*eslint linebreak-style: ["error", "windows"]*/
Refer to the documentation of linebreak-style
:
When developing with a lot of people all having different editors, VCS applications and operating systems it may occur that different line endings are written by either of the mentioned (might especially happen when using the windows and mac versions of SourceTree together).
The linebreaks (new lines) used in windows operating system are usually carriage returns (CR) followed by a line feed (LF) making it a carriage return line feed (CRLF) whereas Linux and Unix use a simple line feed (LF). The corresponding control sequences are
"\n"
(for LF) and"\r\n"
for (CRLF).
This is a rule that is automatically fixable. The --fix
option on the command line automatically fixes problems reported by this rule.
But if you wish to retain CRLF
line-endings in your code (as you're working on Windows) do not use the fix
option.
To help debug, and make your code better, do this:
private void processLine(String[] strings) {
Integer[] intarray=new Integer[strings.length];
int i=0;
for(String str:strings){
try {
intarray[i]=Integer.parseInt(str);
i++;
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Not a number: " + str + " at index " + i, e);
}
}
}
Also, from a code neatness point, you could reduce the lines by doing this:
for (String str : strings)
intarray[i++] = Integer.parseInt(str);
Just use the *args
parameter, which allows you to pass as many arguments as you want after your a,b,c
. You would have to add some logic to map args
->c,d,e,f
but its a "way" of overloading.
def myfunc(a,b, *args, **kwargs):
for ar in args:
print ar
myfunc(a,b,c,d,e,f)
And it will print values of c,d,e,f
Similarly you could use the kwargs
argument and then you could name your parameters.
def myfunc(a,b, *args, **kwargs):
c = kwargs.get('c', None)
d = kwargs.get('d', None)
#etc
myfunc(a,b, c='nick', d='dog', ...)
And then kwargs
would have a dictionary of all the parameters that are key valued after a,b
Are you using virtualenv
? If yes, deactivate the virtualenv. If you are not using, it is already installed widely (system level). Try to upgrade package.
pip install flake8 --upgrade
string hexString = "8E2";
int num = Int32.Parse(hexString, System.Globalization.NumberStyles.HexNumber);
Console.WriteLine(num);
//Output: 2274
Use the function String.Contains();
an example call,
abs.Contains("s"); // to look for lower case s
here is more from MSDN.
If using Visual Code one option is to add this to the settings.json file:
"eslint.options": {
"useEslintrc": false,
"parserOptions": {
"ecmaVersion": 2017
},
"env": {
"es6": true
}
}
Simply:
try {
const cmd = 'git rev-parse --is-inside-work-tree';
execSync(cmd).toString();
} catch (error) {
console.log(`Status Code: ${error.status} with '${error.message}'`;
}
Ref: https://stackoverflow.com/a/43077917/104085
// nodejs
var execSync = require('child_process').execSync;
// typescript
const { execSync } = require("child_process");
try {
const cmd = 'git rev-parse --is-inside-work-tree';
execSync(cmd).toString();
} catch (error) {
error.status; // 0 : successful exit, but here in exception it has to be greater than 0
error.message; // Holds the message you typically want.
error.stderr; // Holds the stderr output. Use `.toString()`.
error.stdout; // Holds the stdout output. Use `.toString()`.
}
Since no context was given to this question and you are a relatively new user, I want to make sure that you are aware that you can have a list of lists. It's not the same as array of list and you asked specifically for that, but nevertheless:
List<List<int>> myList = new List<List<int>>();
you can initialize them through collection initializers like so:
List<List<int>> myList = new List<List<int>>(){{1,2,3},{4,5,6},{7,8,9}};
If you're wondering why the original answer is not working. Well it might be that you're not in the home directory. Try this:
$KAFKA_HOME/bin/kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic test --from-beginning
To stop just some cells being selected use:
cell.userInteractionEnabled = NO;
As well as preventing selection, this also stops tableView:didSelectRowAtIndexPath: being called for the cells that have it set.
You can continue using WebClient to POST (instead of GET, which is the HTTP verb you're currently using with DownloadString), but I think you'll find it easier to work with the (slightly) lower-level classes WebRequest and WebResponse.
There are two parts to this - the first is to post the login form, the second is recovering the "Set-cookie" header and sending that back to the server as "Cookie" along with your GET request. The server will use this cookie to identify you from now on (assuming it's using cookie-based authentication which I'm fairly confident it is as that page returns a Set-cookie header which includes "PHPSESSID").
POSTing to the login form
Form posts are easy to simulate, it's just a case of formatting your post data as follows:
field1=value1&field2=value2
Using WebRequest and code I adapted from Scott Hanselman, here's how you'd POST form data to your login form:
string formUrl = "http://www.mmoinn.com/index.do?PageModule=UsersAction&Action=UsersLogin"; // NOTE: This is the URL the form POSTs to, not the URL of the form (you can find this in the "action" attribute of the HTML's form tag
string formParams = string.Format("email_address={0}&password={1}", "your email", "your password");
string cookieHeader;
WebRequest req = WebRequest.Create(formUrl);
req.ContentType = "application/x-www-form-urlencoded";
req.Method = "POST";
byte[] bytes = Encoding.ASCII.GetBytes(formParams);
req.ContentLength = bytes.Length;
using (Stream os = req.GetRequestStream())
{
os.Write(bytes, 0, bytes.Length);
}
WebResponse resp = req.GetResponse();
cookieHeader = resp.Headers["Set-cookie"];
Here's an example of what you should see in the Set-cookie header for your login form:
PHPSESSID=c4812cffcf2c45e0357a5a93c137642e; path=/; domain=.mmoinn.com,wowmine_referer=directenter; path=/; domain=.mmoinn.com,lang=en; path=/;domain=.mmoinn.com,adt_usertype=other,adt_host=-
GETting the page behind the login form
Now you can perform your GET request to a page that you need to be logged in for.
string pageSource;
string getUrl = "the url of the page behind the login";
WebRequest getRequest = WebRequest.Create(getUrl);
getRequest.Headers.Add("Cookie", cookieHeader);
WebResponse getResponse = getRequest.GetResponse();
using (StreamReader sr = new StreamReader(getResponse.GetResponseStream()))
{
pageSource = sr.ReadToEnd();
}
EDIT:
If you need to view the results of the first POST, you can recover the HTML it returned with:
using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
{
pageSource = sr.ReadToEnd();
}
Place this directly below cookieHeader = resp.Headers["Set-cookie"];
and then inspect the string held in pageSource.
>>> value=42
>>> print "Value is %s"%('"'+str(value)+'"')
Value is "42"
You should not rely on [NSDate date]
for timing purposes since it can over- or under-report the elapsed time. There are even cases where your computer will seemingly time-travel since the elapsed time will be negative! (E.g. if the clock moved backwards during timing.)
According to Aria Haghighi in the "Advanced iOS Gesture Recognition" lecture of the Winter 2013 Stanford iOS course (34:00), you should use CACurrentMediaTime()
if you need an accurate time interval.
Objective-C:
#import <QuartzCore/QuartzCore.h>
CFTimeInterval startTime = CACurrentMediaTime();
// perform some action
CFTimeInterval elapsedTime = CACurrentMediaTime() - startTime;
Swift:
let startTime = CACurrentMediaTime()
// perform some action
let elapsedTime = CACurrentMediaTime() - startTime
The reason is that [NSDate date]
syncs on the server, so it could lead to "time-sync hiccups" which can lead to very difficult-to-track bugs. CACurrentMediaTime()
, on the other hand, is a device time that doesn't change with these network syncs.
You will need to add the QuartzCore framework to your target's settings.
This reloads the datagridview:
Me.ABCListTableAdapter.Fill(Me.ABCLISTDATASET.ABCList)
Hope this helps
Command like this :
composer.phar require intervention/image
error: composer.phar: command not found
I solved the problem by following this process
i set the composer globally and renamed composer.phar
to composer
then run this command composer require intervention/image
. and now it's working fine
If you know the process name you can use:
killall Dock
If you don't you can open Activity Monitor and find it.
I love how people completely miss the request in the original question for an IDE. Linux is NOT an IDE. That's just not what those words mean. I learned c and c++ using vi and gcc and make, and I'm not saying they aren't adequate tools, but they are NOT an IDE. Even if you use more elaborate tools like vim or emacs or whatever fancy editor you want, typing commands on a command line is not an IDE.
Also, you all know make exists as part of visual studio right? The idea that an IDE is "limiting" is just silly if you can use the IDE to speed some things, yet are still able to fall back on command line stuff when needed.
All that said, I'd suggest, as several above have, trying Code blocks. Its got decent code highlighting, a pretty effortless way to create a project, code it, run it, etc, that is the core of a real IDE, and seems fairly stable. Debugging sucks...I have never seen a decent interactive debugger in any linux/unix variant. gdb ain't it. If you're used to visual studio style debugging, you're pretty much out of luck.
Anyway, I'll go pack my things, I know the one-view-only linux crowd will shout this down and run me out of town in no time.
After some years with node, I can say that there are no conventions for the directory/file structure. However most (professional) express applications use a setup like:
/
/bin - scripts, helpers, binaries
/lib - your application
/config - your configuration
/public - your public files
/test - your tests
An example which uses this setup is nodejs-starter.
I personally changed this setup to:
/
/etc - contains configuration
/app - front-end javascript files
/config - loads config
/models - loads models
/bin - helper scripts
/lib - back-end express files
/config - loads config to app.settings
/models - loads mongoose models
/routes - sets up app.get('..')...
/srv - contains public files
/usr - contains templates
/test - contains test files
In my opinion, the latter matches better with the Unix-style directory structure (whereas the former mixes this up a bit).
I also like this pattern to separate files:
lib/index.js
var http = require('http');
var express = require('express');
var app = express();
app.server = http.createServer(app);
require('./config')(app);
require('./models')(app);
require('./routes')(app);
app.server.listen(app.settings.port);
module.exports = app;
lib/static/index.js
var express = require('express');
module.exports = function(app) {
app.use(express.static(app.settings.static.path));
};
This allows decoupling neatly all source code without having to bother dependencies. A really good solution for fighting nasty Javascript. A real-world example is nearby which uses this setup.
Update (filenames):
Regarding filenames most common are short, lowercase filenames. If your file can only be described with two words most JavaScript projects use an underscore as the delimiter.
Update (variables):
Regarding variables, the same "rules" apply as for filenames. Prototypes or classes, however, should use camelCase.
Update (styleguides):
double.Parse("-"); raises an exception, while double.TryParse("-", out parsed); parses to 0 so I guess TryParse does more complex conversions.
We use Akka to process REST calls asynchronously - together with async web server (Netty-based) we can achieve 10 fold improvement on the number of users served per node/server, comparing to traditional thread per user request model.
Tell it to your boss that your AWS hosting bill is going to drop by the factor of 10 and it is a no-brainer! Shh... dont tell it to Amazon though... :)
At Back-end part
Rest service in Controller will have mixed @RequestPart and MultipartFile to serve such Multipart + JSON request.
@RequestMapping(value = "/executesampleservice", method = RequestMethod.POST,
consumes = {"multipart/form-data"})
@ResponseBody
public boolean yourEndpointMethod(
@RequestPart("properties") @Valid ConnectionProperties properties,
@RequestPart("file") @Valid @NotNull @NotBlank MultipartFile file) {
return projectService.executeSampleService(properties, file);
}
At front-end :
formData = new FormData();
formData.append("file", document.forms[formName].file.files[0]);
formData.append('properties', new Blob([JSON.stringify({
"name": "root",
"password": "root"
})], {
type: "application/json"
}));
See in the image (POSTMAN request):
Click to view Postman request in form data for both file and json
Here's what I had to do to setup basic auth on Ubuntu 14.04 (didn't find a guide anywhere else)
/etc/squid3/squid.conf
instead of the super bloated default config file
auth_param basic program /usr/lib/squid3/basic_ncsa_auth /etc/squid3/passwords
auth_param basic realm proxy
acl authenticated proxy_auth REQUIRED
http_access allow authenticated
# Choose the port you want. Below we set it to default 3128.
http_port 3128
Please note the basic_ncsa_auth program instead of the old ncsa_auth
For squid 2.x you need to edit /etc/squid/squid.conf
file and place:
auth_param basic program /usr/lib/squid/digest_pw_auth /etc/squid/passwords
auth_param basic realm proxy
acl authenticated proxy_auth REQUIRED
http_access allow authenticated
sudo htpasswd -c /etc/squid3/passwords username_you_like
and enter a password twice for the chosen username then
sudo service squid3 restart
sudo htpasswd -c /etc/squid/passwords username_you_like
and enter a password twice for the chosen username then
sudo service squid restart
For the many people that asked me: the 2 tools produce different file formats:
htdigest
stores the password in plain text.htpasswd
stores the password hashed (various hashing algos are available)Despite this difference in format basic_ncsa_auth
will still be able to parse a password file generated with htdigest
. Hence you can alternatively use:
sudo htdigest -c /etc/squid3/passwords realm_you_like username_you_like
Beware that this approach is empirical, undocumented and may not be supported by future versions of Squid.
On Ubuntu 14.04 htdigest
and htpasswd
are both available in the [apache2-utils][1]
package.
Similar as above applies, but file paths are different.
Install squid
brew install squid
Start squid service
brew services start squid
Squid config file is stored at /usr/local/etc/squid.conf
.
Comment or remove following line:
http_access allow localnet
Then similar to linux config (but with updated paths) add this:
auth_param basic program /usr/local/Cellar/squid/4.8/libexec/basic_ncsa_auth /usr/local/etc/squid_passwords
auth_param basic realm proxy
acl authenticated proxy_auth REQUIRED
http_access allow authenticated
Note that path to basic_ncsa_auth
may be different since it depends on installed version when using brew
, you can verify this with ls /usr/local/Cellar/squid/
. Also note that you should add the above just bellow the following section:
#
# INSERT YOUR OWN RULE(S) HERE TO ALLOW ACCESS FROM YOUR CLIENTS
#
Now generate yourself a user:password basic auth credential (note: htpasswd
and htdigest
are also both available on MacOS)
htpasswd -c /usr/local/etc/squid_passwords username_you_like
Restart the squid service
brew services restart squid