You would use the Take(N) method.
Since you have replaced the favicon.ico
file physically, there must be a caching issue somewhere. There is a cache in your browser. Force it to get flushed by pressing Ctrl+F5.
If the default icon is still displayed, try another browser with a clean cache (i.e. you haven't visited the page with that browser yet).
Clear Cache Shortcuts: (Source)
Windows
IE:Ctrl+R; Firefox:Ctrl+Shift+R; Chrome:Ctrl+R, or Ctrl+F5, or Shift+F5.
Mac
Safari:?+R; Firefox/Chrome:?+Shift+R.
In addition to previous answers there is one important for me note:
shelve
is JetBrains products feature (such as WebStorm
, PhpStorm
, PyCharm
, etc.). It puts shelved files into .idea/shelf
directory.
stash
is one of git
options. It puts stashed files under the .git
directory.
Case-statements automatically fall through if you don't specify otherwise (by writing break). Therefor you can write
switch(myvar)
{
case 2:
case 5:
{
//your code
break;
}
// etc... }
.blackBox {_x000D_
width: 100%;_x000D_
height: 200px;_x000D_
background-color: #000;_x000D_
position: relative;_x000D_
color: cyan;_x000D_
padding: 20px;_x000D_
box-sizing: border-box;_x000D_
}_x000D_
_x000D_
.blackBox::before {_x000D_
position: absolute;_x000D_
border: 1px dotted #fff;_x000D_
left: 10px;_x000D_
right: 10px;_x000D_
top: 10px;_x000D_
bottom: 10px;_x000D_
content: "";_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<div class="blackBox">Created an inner border box. <br> Working fine all major browsers.</div>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
Easy way to do it without annotations is to use Gson library
Simple as that:
Gson gson = new Gson();
String json = gson.toJson(listaDePontos);
You use css to change the opacity. To cope with IE you'd need something like:
.opaque {
opacity : 0.3;
-ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=30)";
filter: alpha(opacity=30);
}
But the only problem with this is that it means anything inside the container will also be 0.3 opacity. Thus you'll have to change your HTML to have another container, not inside the transparent one, that holds your content.
Otherwise the png technique, would work. Except you'd need a fix for IE6, which in itself could cause problems.
if you can code, write a console app. here is the c# equivalent of what you're after. you can do what you want with the results (split, execute etc):
SqlCommand command = null;
try
{
using (var connection = new SqlConnection("XXXX"))
{
command = new SqlCommand();
command.Connection = connection;
if (command.Connection.State == ConnectionState.Closed) command.Connection.Open();
// Create an instance of StreamReader to read from a file.
// The using statement also closes the StreamReader.
using (StreamReader sr = new StreamReader("C:\\test.txt"))
{
String line;
// Read and display lines from the file until the end of
// the file is reached.
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
command.CommandText = line;
command.ExecuteNonQuery();
Console.Write(" - DONE");
}
}
}
}
catch (Exception e)
{
// Let the user know what went wrong.
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
finally
{
if (command.Connection.State == ConnectionState.Open) command.Connection.Close();
}
Really just answering to add a link which I'm surprised hasn't been mentioned yet: Eric's Lippert's blog entry on "Arrays considered somewhat harmful."
You can judge from the title that it's suggesting using collections wherever practical - but as Marc rightly points out, there are plenty of places where an array really is the only practical solution.
If you used managed wordpress or caching plugins, you have to CLEAR YOUR CACHE before the facebook debugger tool can fetch new info!
I've been pulling my hair out for weeks figuring out why changes I made wouldn't show up in facebook debugger for 24 hours!!!! The fix is I have to go into my wordpress dashboard, click the godaddy icon on the top, and click "flush cache." I think many managed wordpress hosters have a cache to figure out how to clear it and you'll be golden.
Yes, Python does support Short-circuit evaluation, minimal evaluation, or McCarthy evaluation for Boolean operators. It is used to reduce the number of evaluations for computing the output of boolean expression. Example -
Base Functions
def a(x):
print('a')
return x
def b(x):
print('b')
return x
AND
if(a(True) and b(True)):
print(1,end='\n\n')
if(a(False) and b(True)):
print(2,end='\n\n')
AND-OUTPUT
a
b
1
a
OR
if(a(True) or b(False)):
print(3,end='\n\n')
if(a(False) or b(True)):
print(4,end='\n\n')
OR-OUTPUT
a
3
a
b
4
Here is a custom Toast class I made using the above code:
import android.content.Context;
import android.os.CountDownTimer;
import android.widget.Toast;
public class CustomToast extends Toast {
int mDuration;
boolean mShowing = false;
public CustomToast(Context context) {
super(context);
mDuration = 2;
}
/**
* Set the time to show the toast for (in seconds)
* @param seconds Seconds to display the toast
*/
@Override
public void setDuration(int seconds) {
super.setDuration(LENGTH_SHORT);
if(seconds < 2) seconds = 2; //Minimum
mDuration = seconds;
}
/**
* Show the toast for the given time
*/
@Override
public void show() {
super.show();
if(mShowing) return;
mShowing = true;
final Toast thisToast = this;
new CountDownTimer((mDuration-2)*1000, 1000)
{
public void onTick(long millisUntilFinished) {thisToast.show();}
public void onFinish() {thisToast.show(); mShowing = false;}
}.start();
}
}
Here's what I ended up using.
I'm very new to AngularJS, so would love to see better / alternative solutions.
angular.module('formComponents', [])
.directive('formInput', function() {
return {
restrict: 'E',
scope: {},
link: function(scope, element, attrs)
{
var type = attrs.type || 'text';
var required = attrs.hasOwnProperty('required') ? "required='required'" : "";
var htmlText = '<div class="control-group">' +
'<label class="control-label" for="' + attrs.formId + '">' + attrs.label + '</label>' +
'<div class="controls">' +
'<input type="' + type + '" class="input-xlarge" id="' + attrs.formId + '" name="' + attrs.formId + '" ' + required + '>' +
'</div>' +
'</div>';
element.html(htmlText);
}
}
})
Example usage:
<form-input label="Application Name" form-id="appName" required/></form-input>
<form-input type="email" label="Email address" form-id="emailAddress" required/></form-input>
<form-input type="password" label="Password" form-id="password" /></form-input>
Heres the method I used in my logging library: https://github.com/goktugyil/QorumLogs
This method fills html forms inside Google Forms.
var url = NSURL(string: urlstring)
var request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "POST"
request.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.HTTPBody = postData.dataUsingEncoding(NSUTF8StringEncoding)
var connection = NSURLConnection(request: request, delegate: nil, startImmediately: true)
I'd go about this slightly differently. Structure your query to retrieve only what you need and split from there.
So make your query the following:
# vv or Job.find(1) vv
attachments = Attachment.where(job_id: @job.id, file_type: ["logo", "image"])
# or
Job.includes(:attachments).where(id: your_job_id, attachments: { file_type: ["logo", "image"] })
And then partition the data:
@logos, @images = attachments.partition { |attachment| attachment.file_type == "logo" }
That will get the data you're after in a neat and efficient manner.
count(*) is an aggregate function. Aggregate functions need to be grouped for a meaningful results. You can read: count columns group by
return last n lines from your_file.log or .txt
path = File.join(Rails.root, 'your_folder','your_file.log')
last_100_lines = `tail -n 100 #{path}`
A workaround that worked for me (using Backbone.js), was to add "#/" to the end of the redirect URL passed to Facebook. Facebook will keep the provided fragment, and not append its own "_=_".
Upon return, Backbone will remove the "#/" part. For AngularJS, appending "#!" to the return URL should work.
Note that the fragment identifier of the original URL is preserved on redirection (via HTTP status codes 300, 301, 302 and 303) by most browsers, unless the redirect URL also has a fragment identifier. This seems to be recommended behaviour.
If you use a handler script that redirects the user elsewhere, you can append "#" to the redirect URL here to replace the fragment identifier with an empty string.
Using jQuery you can achieve this by doing
var cw = $('.child').width();
$('.child').css({'height':cw+'px'});
Try the following:
int myIndex = MyDataGrid.SelectedIndex;
This will give the index of the row which is currently selected.
Hope this helps
Above answers clearly answer the question but I want to provide another alternative - A different view/approach to solve the similar problem.
You can also use browser extension to remove X-Content-Type-Options
response header for raw.githubusercontent.com
files. There are couple of browser extensions to modify response headers.
If you use Requestly, I can suggest two solutions
Remove
-> Response
-> X-Content-Type-Options
Url
-> Contains
-> raw.githubusercontent.com
raw.githubusercontent.com
with rawgit.com
Check this screenshot for more details
We created a simple JS Fiddle to test out if we can use raw github files as scripts in our code. Here is the Fiddle with the following code
<center id="msg"></center>
<script src="https://raw.githubusercontent.com/sachinjain024/practicebook/master/web-extensions-master/storage/background.js"></script>
<script>
try {
if (typeof BG.Methods !== 'undefoned') {
document.getElementById('msg').innerHTML = 'Script evaluated successfully!';
}
} catch (e) {
document.getElementById('msg').innerHTML = 'Problem evaluating script';
}
</script>
If you see Script evaluated successfully!
, It means you are able to use raw github file in your code
Otherwise Problem evaluating script
indicates that there is some problem while executing script from raw github source.
I also wrote an article on Requestly blog about this. Please refer it for more details.
Hope it helps!!
Disclaimer: I am author of Requestly So you can blame for anything you don't like.
As others have noted, you can't have immutable arrays in Java.
If you absolutely need a method that returns an array that doesn't influence the original array, then you'd need to clone the array each time:
public int[] getFooArray() {
return fooArray == null ? null : fooArray.clone();
}
Obviously this is rather expensive (as you'll create a full copy each time you call the getter), but if you can't change the interface (to use a List
for example) and can't risk the client changing your internals, then it may be necessary.
This technique is called making a defensive copy.
Just use Kotlin!
val list = listOf(user1, user2, user3)
val maxDate = list.maxBy { it.date }?.date
If the array is unsorted, you will need to use linear search.
Simply use the base transpose function t
, wrapped with as.data.frame
:
final_df <- as.data.frame(t(starting_df))
final_df
A B C D
a 1 2 3 4
b 0.02 0.04 0.06 0.08
c Aaaa Bbbb Cccc Dddd
Above updated. As docendo discimus pointed out, t
returns a matrix. As Mark suggested wrapping it with as.data.frame
gets back a data frame instead of a matrix. Thanks!
Working fiddle:
$.ajax({
url: 'https://api.flightstats.com/flex/schedules/rest/v1/jsonp/flight/AA/100/departing/2013/10/4?appId=19d57e69&appKey=e0ea60854c1205af43fd7b1203005d59',
dataType: 'JSONP',
jsonpCallback: 'callback',
type: 'GET',
success: function (data) {
console.log(data);
}
});
I had to manually set the callback to callback
, since that's all the remote service seems to support. I also changed the url to specify that I wanted jsonp.
this work for me, thanks. I want change text size only not change font name.
var fontSizeButtonBig:Int = 30
btnMenu9.titleLabel?.font = .systemFont(ofSize: CGFloat(fontSizeButtonBig))
You are working way too hard. Your entire script should be:
if mkdir "$lockdir" 2> /dev/null; then
echo lock acquired
else
echo could not acquire lock >&2
fi
but even that is probably too verbose. I would code it:
mkdir "$lockdir" || exit 1
but the resulting error message is a bit obscure.
I wrote this function which returns linked list of separated strings by specific delimiter. Pure free pascal without modules.
Program split_f;
type
PTItem = ^TItem;
TItem = record
str : string;
next : PTItem;
end;
var
s : string;
strs : PTItem;
procedure split(str : string;delim : char;var list : PTItem);
var
i : integer;
buff : PTItem;
begin
new(list);
buff:= list;
buff^.str:='';
buff^.next:=nil;
for i:=1 to length(str) do begin
if (str[i] = delim) then begin
new(buff^.next);
buff:=buff^.next;
buff^.str := '';
buff^.next := nil;
end
else
buff^.str:= buff^.str+str[i];
end;
end;
procedure print(var list:PTItem);
var
buff : PTItem;
begin
buff := list;
while buff<>nil do begin
writeln(buff^.str);
buff:= buff^.next;
end;
end;
begin
s := 'Hi;how;are;you?';
split(s, ';', strs);
print(strs);
end.
In GitExtensions you can select both branches in revision grid with Ctrl pressed. Then you can see files that differ between those branches. When you select a file you will see diff for it.
Taken from here
Take a look at this tutorial. Also you can parse above json like :
JSONArray arr = new JSONArray(yourJSONresponse);
List<String> list = new ArrayList<String>();
for(int i = 0; i < arr.length(); i++){
list.add(arr.getJSONObject(i).getString("name"));
}
Using System Preferences:
Step 1: Click the Apple icon (at the top left of the screen) and select System Preferences.
Step 2: Click Network.
Step 3: Select your network connection and then click Advanced.
Step 4: Select the TCP/IP tab and find your gateway IP address listed next to Router.
I realize its an old question, but this came up in my searches. Had a similar issue for an MVC application recently built, deployed for the first time, and Authentication mechanism wasn't completely hashed out.
It wasn't an IIS setting in my case, it was a Controller that was not [AllowAnonymous]
decorated. I was using a Render.Action/Html.Action in a Layout.cshtml and the User was unauthenticated. So the Layout tried to load an Authenticated Action in an UnAuthenticated context.
Once I updated the action to AllowAnonymous, the problem went away, and this is what led me to it.
Hope this helps someone.
Use 1) form with tokens 2) Check form to form delay with IP address 3) Block IP (optional)
Apart of directly writing HTML on the PrintWriter obtained from the response (which is the standard way of outputting HTML from a Servlet), you can also include an HTML fragment contained in an external file by using a RequestDispatcher:
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("HTML from an external file:");
request.getRequestDispatcher("/pathToFile/fragment.html")
.include(request, response);
out.close();
}
WEEK
select TRUNC(sysdate, 'iw') AS iso_week_start_date,
TRUNC(sysdate, 'iw') + 7 - 1/86400 AS iso_week_end_date
from dual;
MONTH
select
TRUNC (sysdate, 'mm') AS month_start_date,
LAST_DAY (TRUNC (sysdate, 'mm')) + 1 - 1/86400 AS month_end_date
from dual;
Also ran into this error message, but the root cause was of a different flavor from those referenced in the other answers here.
Generic answer: Make sure that once hibernate loads an entity, no code changes the primary key value in that object in any way. When hibernate flushes all changes back to the database, it throws this exception because the primary key changed. If you don't do it explicitly, look for places where this may happen unintentionally, perhaps on related entities that only have LAZY loading configured.
In my case, I am using a mapping framework (MapStruct) to update an entity. In the process, also other referenced entities were being updates as mapping frameworks tend to do that by default. I was later replacing the original entity with new one (in DB terms, changed the value of the foreign key to reference a different row in the related table), the primary key of the previously-referenced entity was already updated, and hibernate attempted to persist this update on flush.
I don't know if it's a good answer, but I was able to solve this problem by running my application under an AppDomain with an identity of "Local System".
simple way for new font awesome
<div class="input-group">
<input type="text" class="form-control" placeholder="Search" name="txtSearch" >
<div class="input-group-btn">
<button class="btn btn-default" type="submit"><i class="fas fa-search"></i></button>
</div>
</div>
Assuming you are in the directory where myJar.jar
file is and that myClass
has a public static void main()
method on it:
You use the following command line:
java -cp ./myJar.jar myClass
Where:
myJar.jar
is in the current path, note that .
isn't in the current path on most systems. A fully qualified path is preferred here as well.
myClass
is a fully qualified package path to the class, the example assumes that myClass
is in the default package which is bad practice, if it is in a nested package it would be com.mycompany.mycode.myClass
.
Tables work differently; sometimes counter-intuitively.
The solution is to use width
on the table cells instead of max-width
.
Although it may sound like in that case the cells won't shrink below the given width, they will actually.
with no restrictions on c, if you give the table a width of 70px, the widths of a, b and c will come out as 16, 42 and 12 pixels, respectively.
With a table width of 400 pixels, they behave like you say you expect in your grid above.
Only when you try to give the table too small a size (smaller than a.min+b.min+the content of C) will it fail: then the table itself will be wider than specified.
I made a snippet based on your fiddle, in which I removed all the borders and paddings and border-spacing, so you can measure the widths more accurately.
table {_x000D_
width: 70px;_x000D_
}_x000D_
_x000D_
table, tbody, tr, td {_x000D_
margin: 0;_x000D_
padding: 0;_x000D_
border: 0;_x000D_
border-spacing: 0;_x000D_
}_x000D_
_x000D_
.a, .c {_x000D_
background-color: red;_x000D_
}_x000D_
_x000D_
.b {_x000D_
background-color: #F77;_x000D_
}_x000D_
_x000D_
.a {_x000D_
min-width: 10px;_x000D_
width: 20px;_x000D_
max-width: 20px;_x000D_
}_x000D_
_x000D_
.b {_x000D_
min-width: 40px;_x000D_
width: 45px;_x000D_
max-width: 45px;_x000D_
}_x000D_
_x000D_
.c {}
_x000D_
<table>_x000D_
<tr>_x000D_
<td class="a">A</td>_x000D_
<td class="b">B</td>_x000D_
<td class="c">C</td>_x000D_
</tr>_x000D_
</table>
_x000D_
You can use the -B
and -A
to print lines before and after the match.
grep -i -B 10 'error' data
Will print the 10 lines before the match, including the matching line itself.
If you are using a string resource xml file (supports HTML tags), it can be done using<b> </b>
, <i> </i>
and <u> </u>
.
<resources>
<string name="your_string_here">
This is an <u>underline</u>.
</string>
</resources>
If you want to underline something from code use:
TextView tv = (TextView) view.findViewById(R.id.tv);
SpannableString content = new SpannableString("Content");
content.setSpan(new UnderlineSpan(), 0, content.length(), 0);
tv.setText(content);
Hope this helps
Just point to the dictionary at given key and assign a new value:
myDictionary[myKey] = myNewValue;
You can use
start "" "%USERPROFILE%\Desktop\BGInfo\bginfo.exe" "%USERPROFILE%\Desktop\BGInfo\dc_bginfo.bgi"
or
start "" /D "%USERPROFILE%\Desktop\BGInfo" bginfo.exe dc_bginfo.bgi
or
"%USERPROFILE%\Desktop\BGInfo\bginfo.exe" "%USERPROFILE%\Desktop\BGInfo\dc_bginfo.bgi"
or
cd /D "%USERPROFILE%\Desktop\BGInfo"
bginfo.exe dc_bginfo.bgi
Help on commands start and cd is output by executing in a command prompt window help start
or start /?
and help cd
or cd /?
.
But I do not understand why you need a batch file at all for starting the application with the additional parameter. Create a shortcut (*.lnk) on your desktop for this application. Then right click on the shortcut, left click on Properties and append after a space character "%USERPROFILE%\Desktop\BGInfo\dc_bginfo.bgi"
as parameter.
I met it when import a ViewController.m in TableViewController. Try to delete '#import "ViewController.m"' if it exited. Hope this help!
If you are running macOS X and run platform.system()
you get darwin
because macOS X is built on Apple's Darwin OS. Darwin is the kernel of macOS X and is essentially macOS X without the GUI.
HTML:
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ipsa omnis obcaecati dolore reprehenderit praesentium. Nisi eius deleniti voluptates quis esse deserunt magni eum commodi nostrum facere pariatur sed eos voluptatum?
</p><span class="small-text">George Nelson 1955</span>
CSS:
p {font-size:24px; font-weight: 300; -webkit-font-smoothing: subpixel-antialiased;}
p span {font-size:16px; font-style: italic; margin-top:50px;}
.small-text{
font-size: 12px;
font-style: italic;
}
The other answers are good if you are dealing only with numbers using the format string, but this is good when you may have strings that need to be padded (although admittedly a little diffent than the question asked, seems similar in spirit). Also, be careful if the string is longer than the pad.
let str = "a str"
let padAmount = max(10, str.count)
String(repeatElement("-", count: padAmount - str.count)) + str
Output "-----a str"
My problem was that I needed to Reset Window Layout.
One really simple option is to install a Windows bash shell such as MinGW and use that:
There is a little bit of a learning curve as you will need to use Unix command line functionality, but you will love the power of it and you can set the console character set to UTF-8.
Of course you also get all the usual *nix goodies like grep, find, less, etc.
If you have XDocument it is easier to use LINQ-to-XML:
var document = XDocument.Load(fileName);
var name = document.Descendants(XName.Get("Name", @"http://demo.com/2011/demo-schema")).First().Value;
If you are sure that XPath is the only solution you need:
using System.Xml.XPath;
var document = XDocument.Load(fileName);
var namespaceManager = new XmlNamespaceManager(new NameTable());
namespaceManager.AddNamespace("empty", "http://demo.com/2011/demo-schema");
var name = document.XPathSelectElement("/empty:Report/empty:ReportInfo/empty:Name", namespaceManager).Value;
Just don't perform e.preventDefault();
, or perform it conditionally.
You certainly can't alter when the original event action occurs.
If you want to "recreate" the original UI event some time later (say, in the callback for an AJAX request) then you'll just have to fake it some other way (like in vzwick's answer)... though I'd question the usability of such an approach.
Actually a more refined solution is use the build-in function sumif, this function does exactly what you need, will only sum those expenses of a specified month.
example
=SUMIF(A2:A100,"=January",B2:B100)
This should work:
git show branch:file
Where branch can be any ref (branch, tag, HEAD, ...) and file is the full path of the file. To export it you could use
git show branch:file > exported_file
You should also look at VonC's answers to some related questions:
UPDATE 2015-01-19:
Nowadays you can use relative paths with git show a1b35:./file.txt
.
Also You Can Use Server.Execute
public void iterateStreamAPI(Map<String, Integer> map) {
map.entrySet().stream().forEach(e -> System.out.println(e.getKey() + ":"e.getValue()));
}
How to Enable USB Debugging for LG Optimus (LGD415). Android version 4.4.2 (KitKat)
Go to this website and download the drivers to your phone:
http://www.lg.com/us/support/mobile-support
For example, mine would be:
http://www.lg.com/us/support-mobile/lg-LGD415RD. Then click on “Software Update & Drivers”
On your phone, you need to enable USB debugging. To do so,
Go to “Settings”.
Go to “About Phone”
Go to “Software Information”
Tap “Build number” five times.
A pop-up will appear saying “You are now a developer”. Your’re not done yet.
Go back to your phone’s home page by pushing the home button.
Go to “Settings”.
Go to “Developer options”
Click the “USB debugging- Turn on debug mode when USB is connected”. A blue checkmark will appear.
(EDIT: If USB Debugging is greyed out, unplug your phone. USB Debugging should no longer be greyed out. If it is not greyed out, check the box and plug your phone into your PC.)
Unplug your phone from your PC. Then plug it back in. On the pop-up, make sure you set it to “Media Sync (MTP)”.
Now your phone will show up on an option when you want to run your app in Eclipse.
(Look for dialog box on phone and agree to allow debugging connection with your computer.)
(Also, go to Control Panel | Device Manager and make sure there are TWO entries for your phone, similar to those expanded below.)
I agree with the current answers, I just wanna add little more information.
A new feature has been added to Laravel 5.3 and above version that will allow you to back out a single migration:
php artisan migrate:rollback --step=1
after, Manually delete the migration file under database/migrations/my_migration_file_name.php
This is a great feature for when you run a migration
In this way, you can safely remove the migration in laravel only in 2 step
Initialize it first
MainActivity mActivity= new MainActivity();
Then you can continue
mActivity.startChronometer();
Try:
InputStream inputStream= // Your InputStream from your database.
Reader reader = new InputStreamReader(inputStream,"UTF-8");
InputSource is = new InputSource(reader);
is.setEncoding("UTF-8");
saxParser.parse(is, handler);
If it's anything else than UTF-8, just change the encoding part for the good one.
You can use upstream headers (named starting with $http_) and additional custom headers. For example:
add_header X-Upstream-01 $http_x_upstream_01;
add_header X-Hdr-01 txt01;
next, go to console and make request with user's header:
curl -H "X-Upstream-01: HEADER1" -I http://localhost:11443/
the response contains X-Hdr-01, seted by server and X-Upstream-01, seted by client:
HTTP/1.1 200 OK
Server: nginx/1.8.0
Date: Mon, 30 Nov 2015 23:54:30 GMT
Content-Type: text/html;charset=UTF-8
Connection: keep-alive
X-Hdr-01: txt01
X-Upstream-01: HEADER1
On modern browsers you can use wheel event
:
// Content is the element you want to apply the wheel scroll effect to
content.addEventListener('wheel', function(e) {
const step = 100; // How many pixels to scroll
if (e.deltaY > 0) // Scroll down
content.scrollTop += step;
else // Scroll up
content.scrollTop -= step;
});
Below is the code to rotate or re size your image in android
public class bitmaptest extends Activity {
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
LinearLayout linLayout = new LinearLayout(this);
// load the origial BitMap (500 x 500 px)
Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(),
R.drawable.android);
int width = bitmapOrg.width();
int height = bitmapOrg.height();
int newWidth = 200;
int newHeight = 200;
// calculate the scale - in this case = 0.4f
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
// createa matrix for the manipulation
Matrix matrix = new Matrix();
// resize the bit map
matrix.postScale(scaleWidth, scaleHeight);
// rotate the Bitmap
matrix.postRotate(45);
// recreate the new Bitmap
Bitmap resizedBitmap = Bitmap.createBitmap(bitmapOrg, 0, 0,
width, height, matrix, true);
// make a Drawable from Bitmap to allow to set the BitMap
// to the ImageView, ImageButton or what ever
BitmapDrawable bmd = new BitmapDrawable(resizedBitmap);
ImageView imageView = new ImageView(this);
// set the Drawable on the ImageView
imageView.setImageDrawable(bmd);
// center the Image
imageView.setScaleType(ScaleType.CENTER);
// add ImageView to the Layout
linLayout.addView(imageView,
new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT
)
);
// set LinearLayout as ContentView
setContentView(linLayout);
}
}
You can also check this link for details : http://www.anddev.org/resize_and_rotate_image_-_example-t621.html
For <input type="datetime" value="" ...
A string representing a global date and time.
Value: A valid date-time as defined in [RFC 3339], with these additional qualifications:
•the literal letters T and Z in the date/time syntax must always be uppercase
•the date-fullyear production is instead defined as four or more digits representing a number greater than 0
Examples:
1990-12-31T23:59:60Z
1996-12-19T16:39:57-08:00
http://www.w3.org/TR/html-markup/input.datetime.html#input.datetime.attrs.value
Update:
This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it.
The HTML was a control for entering a date and time (hour, minute, second, and fraction of a second) as well as a timezone. This feature has been removed from WHATWG HTML, and is no longer supported in browsers.
Instead, browsers are implementing (and developers are encouraged to use) the datetime-local input type.
Why is HTML5 input type datetime removed from browsers already supporting it?
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/datetime
Set up a device for development https://developer.android.com/studio/run/device.html#setting-up
Enable developer options and debugging https://developer.android.com/studio/debug/dev-options.html#enable
Optional
To add to an existing answer in ASP.NET Core >= 1.0 you can
return Unauthorized();
return Unauthorized(object value);
To pass info to the client you can do a call like this:
return Unauthorized(new { Ok = false, Code = Constants.INVALID_CREDENTIALS, ...});
On the client besides the 401 response you will have the passed data too. For example on most clients you can await response.json()
to get it.
Use the value
property of the <select>
element. For example:
var value = document.getElementById('your_select_id').value;
alert(value);
const dayOfYear = date => {_x000D_
const myDate = new Date(date);_x000D_
const year = myDate.getFullYear();_x000D_
const firstJan = new Date(year, 0, 1);_x000D_
const differenceInMillieSeconds = myDate - firstJan;_x000D_
return (differenceInMillieSeconds / (1000 * 60 * 60 * 24) + 1);_x000D_
};_x000D_
_x000D_
const result = dayOfYear("2019-2-01");_x000D_
console.log(result);
_x000D_
Since I18n is the Rails core feature starting from version 2.2 you can use its localize-method. By applying the forementioned strftime %-variables you can specify the desired format under config/locales/en.yml
(or whatever language), in your case like this:
time:
formats:
default: '%FT%T'
Or if you want to use this kind of format in a few specific places you can refer it as a variable like this
time:
formats:
specific_format: '%FT%T'
After that you can use it in your views like this:
l(Mode.last.created_at, format: :specific_format)
I created a method just for that. I use it any time I need to manually update a ListView
. Hopefully this gives you an idea of how to implement your own
public static void UpdateListView(List<SomeObject> SomeObjects, ListView ListVw)
{
if(ListVw != null)
{
final YourAdapter adapter = (YourAdapter) ListVw.getAdapter();
//You'll have to create this method in your adapter class. It's a simple setter.
adapter.SetList(SomeObjects);
adapter.notifyDataSetChanged();
}
}
I'm using an adapter that inherites from BaseAdapter
. Should work for any other type of adapter.
edittext.requestFocus()
works for me in my Activity
and Fragment
Your first problem is that you are passing -3 to the 2nd parameter of Columns.Add. It needs to be -2 for it to auto-size the column. Source: http://msdn.microsoft.com/en-us/library/system.windows.forms.listview.columns.aspx (look at the comments on the code example at the bottom)
private void initListView()
{
// Add columns
lvRegAnimals.Columns.Add("Id", -2,HorizontalAlignment.Left);
lvRegAnimals.Columns.Add("Name", -2, HorizontalAlignment.Left);
lvRegAnimals.Columns.Add("Age", -2, HorizontalAlignment.Left);
}
You can also use the other overload, Add(string). E.g:
lvRegAnimals.Columns.Add("Id");
lvRegAnimals.Columns.Add("Name");
lvRegAnimals.Columns.Add("Age");
Reference for more overloads: http://msdn.microsoft.com/en-us/library/system.windows.forms.listview.columnheadercollection.aspx
Second, to add items to the ListView, you need to create instances of ListViewItem and add them to the listView's Items collection. You will need to use the string[] constructor.
var item1 = new ListViewItem(new[] {"id123", "Tom", "24"});
var item2 = new ListViewItem(new[] {person.Id, person.Name, person.Age});
lvRegAnimals.Items.Add(item1);
lvRegAnimals.Items.Add(item2);
You can also store objects in the item's Tag property.
item2.Tag = person;
And then you can extract it
var person = item2.Tag as Person;
Let me know if you have any questions and I hope this helps!
You can specify the -t
option (--target
) to specify the destination directory. See pip install --help
for detailed information. This is the command you need:
pip install -t path_to_your_home package-name
for example, for installing say mxnet, in my $HOME
directory, I type:
pip install -t /home/foivos/ mxnet
$(selector).change()
Longer slower alternative, better for abstraction.
$(selector).trigger("change")
I had a button in my layout.xml that was defined as a View as in:
final View myButton = findViewById(R.id.button1);
I was not able to change the text on it until I also defined it as a button:
final View vButton = findViewById(R.id.button1);
final Button bButton = (Button) findViewById(R.id.button1);
When I needed to change the text, I used the bButton.setText("Some Text");
and when I wanted to alter the view, I used the vButton.
Worked great!
Your comparison function between old value and new value is having some issue. It is better not to complicate things so much, as it will increase your debugging effort later. You should keep it simple.
The best way is to create a person-component
and watch every person separately inside its own component, as shown below:
<person-component :person="person" v-for="person in people"></person-component>
Please find below a working example for watching inside person component. If you want to handle it on parent side, you may use $emit
to send an event upwards, containing the id
of modified person.
Vue.component('person-component', {_x000D_
props: ["person"],_x000D_
template: `_x000D_
<div class="person">_x000D_
{{person.name}}_x000D_
<input type='text' v-model='person.age'/>_x000D_
</div>`,_x000D_
watch: {_x000D_
person: {_x000D_
handler: function(newValue) {_x000D_
console.log("Person with ID:" + newValue.id + " modified")_x000D_
console.log("New age: " + newValue.age)_x000D_
},_x000D_
deep: true_x000D_
}_x000D_
}_x000D_
});_x000D_
_x000D_
new Vue({_x000D_
el: '#app',_x000D_
data: {_x000D_
people: [_x000D_
{id: 0, name: 'Bob', age: 27},_x000D_
{id: 1, name: 'Frank', age: 32},_x000D_
{id: 2, name: 'Joe', age: 38}_x000D_
]_x000D_
}_x000D_
});
_x000D_
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>_x000D_
<body>_x000D_
<div id="app">_x000D_
<p>List of people:</p>_x000D_
<person-component :person="person" v-for="person in people"></person-component>_x000D_
</div>_x000D_
</body>
_x000D_
Here's a simple example that can demonstrate the difference.
The main difference is that array will make a copy of the original data and using different object we can modify the data in the original array.
import numpy as np
a = np.arange(0.0, 10.2, 0.12)
int_cvr = np.asarray(a, dtype = np.int64)
The contents in array (a), remain untouched, and still, we can perform any operation on the data using another object without modifying the content in original array.
You can check internet with below code as well:
public class CheckInternetConnection {
public Context context = null;
public CheckInternetConnection(Context ctx) {
this.context = ctx;
}
public boolean CheckInternet() {
return isOnline();
}
public Boolean isOnline()
{
try {
if(isNetAvailable(context))
return true;
else
{
try {
URL url = new URL("http://www.google.com");
HttpURLConnection urlc = (HttpURLConnection) url
.openConnection();
urlc.setRequestProperty("User-Agent", "Test");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(3000); // This is time limit if the
// connection time limit
try {
urlc.connect();
Log.e("TAG", " urlc ----------" + urlc.getResponseCode());
if (urlc.getResponseCode() == 200) {
return true;
}
}catch (Exception e){
e.printStackTrace();
}
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}catch (Exception e){
e.printStackTrace();
}
return false;
}
public synchronized static boolean isNetAvailable(Context context){
try{
boolean isNetAvailable=false;
if ( context != null )
{
ConnectivityManager mgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if ( mgr != null )
{
boolean mobileNetwork = false;
boolean wifiNetwork = false;
boolean wiMaxNetwork = false;
boolean mobileNetworkConnecetd = false;
boolean wifiNetworkConnecetd = false;
boolean wiMaxNetworkConnected = false;
NetworkInfo mobileInfo = mgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
NetworkInfo wifiInfo = mgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
NetworkInfo wiMaxInfo = mgr.getNetworkInfo(ConnectivityManager.TYPE_WIMAX);
if ( mobileInfo != null )
mobileNetwork = mobileInfo.isAvailable();
if ( wifiInfo != null )
wifiNetwork = wifiInfo.isAvailable();
if(wiMaxInfo != null)
wiMaxNetwork = wiMaxInfo.isAvailable();
if(wifiNetwork == true)
wifiNetworkConnecetd = wifiInfo.isConnectedOrConnecting();
if(mobileNetwork == true)
mobileNetworkConnecetd = mobileInfo.isConnectedOrConnecting();
if(wiMaxNetwork == true)
wiMaxNetworkConnected = wiMaxInfo.isConnectedOrConnecting();
isNetAvailable = ( mobileNetworkConnecetd || wifiNetworkConnecetd || wiMaxNetworkConnected );
}
}
return isNetAvailable;
}catch(NullPointerException e)
{
return false;
}catch(Exception e)
{
return false;
}
}
}
In such a small cases where difference is less than 0 milliseconds you can get difference in nano seconds as well.
System.nanoTime()
This is a function that zips a whole folder and its contents in to a zip file and you can use it simple like this :
addzip ("path/folder/" , "/path2/folder.zip" );
function :
// compress all files in the source directory to destination directory
function create_zip($files = array(), $dest = '', $overwrite = false) {
if (file_exists($dest) && !$overwrite) {
return false;
}
if (($files)) {
$zip = new ZipArchive();
if ($zip->open($dest, $overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
return false;
}
foreach ($files as $file) {
$zip->addFile($file, $file);
}
$zip->close();
return file_exists($dest);
} else {
return false;
}
}
function addzip($source, $destination) {
$files_to_zip = glob($source . '/*');
create_zip($files_to_zip, $destination);
echo "done";
}
I'm using IronPython here (same as .NET API) and reading the file as UTF-8 in order to properly handle the BOM fixed the problem for me:
xmlFile = Path.Combine(directory_str, 'file.xml')
doc = XPathDocument(XmlTextReader(StreamReader(xmlFile.ToString(), Encoding.UTF8)))
It would work as well with the XmlDocument
:
doc = XmlDocument()
doc.Load(XmlTextReader(StreamReader(xmlFile.ToString(), Encoding.UTF8)))
You can use PyVirtualDisplay (a Python wrapper for Xvfb) to run headless WebDriver tests.
#!/usr/bin/env python
from pyvirtualdisplay import Display
from selenium import webdriver
display = Display(visible=0, size=(800, 600))
display.start()
# now Firefox will run in a virtual display.
# you will not see the browser.
browser = webdriver.Firefox()
browser.get('http://www.google.com')
print browser.title
browser.quit()
display.stop()
You can also use xvfbwrapper, which is a similar module (but has no external dependencies):
from xvfbwrapper import Xvfb
vdisplay = Xvfb()
vdisplay.start()
# launch stuff inside virtual display here
vdisplay.stop()
or better yet, use it as a context manager:
from xvfbwrapper import Xvfb
with Xvfb() as xvfb:
# launch stuff inside virtual display here.
# It starts/stops in this code block.
You need to call self.a()
to invoke a
from b
. a
is not a global function, it is a method on the class.
You may want to read through the Python tutorial on classes some more to get the finer details down.
I do not know why, but the image should not be duplicated, tripled, etc ... should remove the previous one and load it again but with another rotation data. This is my code:
data.csv enter image description here
d3.csv("data/data.csv").then(function(data){
//console.log(data);
// Clean data
formattedData = data.map(function(id){
id.rot_1 = +id.rot_1;
id.trans_1 = +id.trans_1;
return id;
});
// First run of the visualization
update(formattedData[0]);})
$("#play-button")
.on("click", function(){
var button = $(this);
if (button.text() == "Play"){
button.text("Pause");
interval = setInterval(step, 1000);
}
else {
button.text("Play");
clearInterval(interval);
}})
function step(){
// At the end of our data, loop back
time = (time < 76) ? time+1 : 0
update(formattedData[time]); }
function update(data) {
// Standard transition time for the visualization
var t = d3.transition()
.duration(1000);
//console.log(d3.selectAll(data));
//console.log(data)
// original
var imgs1 = g.append("image") // en vez de g es svg
.attr("xlink:href", "img/picturetest.png");
// EXIT old elements not present in new data.
imgs1.exit()
.attr("class", "exit")
.selectAll("svg:image")
.remove();
//console.log(data)
// ENTER new elements present in new data.
imgs1.enter()
.append("svg:image") // svg:image
//.attr("xlink:href", "img/picturetest.png")
.attr("class", "enter")
.merge(imgs1)
.transition(t)
.attr("x", 0) // 150
.attr("y", 0) // 80
.attr("width", 200)
.attr("height", 200)
.attr("transform", "rotate("+data.rot_1+") translate("+data.trans_1+")" ); }`
var test = {'red':'#FF0000', 'blue':'#0000FF'};_x000D_
delete test.blue; // or use => delete test['blue'];_x000D_
console.log(test);
_x000D_
this deletes test.blue
Latest version of SpringBoot makes uploading multiple files very easy also. On the browser side you just need the standard HTML upload form, but with multiple input elements (one per file to upload, which is very important), all having the same element name (name="files" for the example below)
Then in your Spring @Controller class on the server all you need is something like this:
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public @ResponseBody ResponseEntity<?> upload(
@RequestParam("files") MultipartFile[] uploadFiles) throws Exception
{
...now loop over all uploadFiles in the array and do what you want
return new ResponseEntity<>(HttpStatus.OK);
}
Those are the tricky parts. That is, knowing to create multiple input elements each named "files", and knowing to use a MultipartFile[] (array) as the request parameter are the tricky things to know, but it's just that simple. I won't get into how to process a MultipartFile entry, because there's plenty of docs on that already.
I think points one (somebody else using your lock) and two (all methods using the same lock needlessly) can happen in any fairly large application. Especially when there's no good communication between developers.
It's not cast in stone, it's mostly an issue of good practice and preventing errors.
This can also be done in the GUI:
Adding \n
and/or \r
in the middle of the string, and having a very long line of code, like in second example, doesn't feel right : when you read the code, you don't see the result, and you have to scroll.
In this kind of situations, I always use Heredoc (Or Nowdoc, if using PHP >= 5.3) : easy to write, easy to read, no need for super-long lines, ...
For instance :
$var = 'World';
$str = <<<MARKER
this is a very
long string that
doesn't require
horizontal scrolling,
and interpolates variables :
Hello, $var!
MARKER;
Just one thing : the end marker (and the ';
' after it) must be the only thing on its line : no space/tab before or after !
Here is the root cause of java 1.5:
Also note that at present the default source setting is 1.5 and the default target setting is 1.5, independently of the JDK you run Maven with. If you want to change these defaults, you should set source and target.
Reference : Apache Mavem Compiler Plugin
Following are the details:
Plain pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.pluralsight</groupId>
<artifactId>spring_sample</artifactId>
<version>1.0-SNAPSHOT</version>
</project>
Following plugin is taken from an expanded POM version(Effective POM),
This can be get by this command from the command line C:\mvn help:effective-pom
I just put here a small snippet instead of an entire pom.
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<executions>
<execution>
<id>default-compile</id>
<phase>compile</phase>
<goals>
<goal>compile</goal>
</goals>
</execution>
<execution>
<id>default-testCompile</id>
<phase>test-compile</phase>
<goals>
<goal>testCompile</goal>
</goals>
</execution>
</executions>
</plugin>
Even here you don't see where is the java version defined, lets dig more...
Download the plugin, Apache Maven Compiler Plugin » 3.1 as its available in jar and open it in any file compression tool like 7-zip
Traverse the jar and findout
plugin.xml
file inside folder
maven-compiler-plugin-3.1.jar\META-INF\maven\
Now you will see the following section in the file,
<configuration>
<basedir implementation="java.io.File" default-value="${basedir}"/>
<buildDirectory implementation="java.io.File" default-value="${project.build.directory}"/>
<classpathElements implementation="java.util.List" default-value="${project.testClasspathElements}"/>
<compileSourceRoots implementation="java.util.List" default-value="${project.testCompileSourceRoots}"/>
<compilerId implementation="java.lang.String" default-value="javac">${maven.compiler.compilerId}</compilerId>
<compilerReuseStrategy implementation="java.lang.String" default-value="${reuseCreated}">${maven.compiler.compilerReuseStrategy}</compilerReuseStrategy>
<compilerVersion implementation="java.lang.String">${maven.compiler.compilerVersion}</compilerVersion>
<debug implementation="boolean" default-value="true">${maven.compiler.debug}</debug>
<debuglevel implementation="java.lang.String">${maven.compiler.debuglevel}</debuglevel>
<encoding implementation="java.lang.String" default-value="${project.build.sourceEncoding}">${encoding}</encoding>
<executable implementation="java.lang.String">${maven.compiler.executable}</executable>
<failOnError implementation="boolean" default-value="true">${maven.compiler.failOnError}</failOnError>
<forceJavacCompilerUse implementation="boolean" default-value="false">${maven.compiler.forceJavacCompilerUse}</forceJavacCompilerUse>
<fork implementation="boolean" default-value="false">${maven.compiler.fork}</fork>
<generatedTestSourcesDirectory implementation="java.io.File" default-value="${project.build.directory}/generated-test-sources/test-annotations"/>
<maxmem implementation="java.lang.String">${maven.compiler.maxmem}</maxmem>
<meminitial implementation="java.lang.String">${maven.compiler.meminitial}</meminitial>
<mojoExecution implementation="org.apache.maven.plugin.MojoExecution">${mojoExecution}</mojoExecution>
<optimize implementation="boolean" default-value="false">${maven.compiler.optimize}</optimize>
<outputDirectory implementation="java.io.File" default-value="${project.build.testOutputDirectory}"/>
<showDeprecation implementation="boolean" default-value="false">${maven.compiler.showDeprecation}</showDeprecation>
<showWarnings implementation="boolean" default-value="false">${maven.compiler.showWarnings}</showWarnings>
<skip implementation="boolean">${maven.test.skip}</skip>
<skipMultiThreadWarning implementation="boolean" default-value="false">${maven.compiler.skipMultiThreadWarning}</skipMultiThreadWarning>
<source implementation="java.lang.String" default-value="1.5">${maven.compiler.source}</source>
<staleMillis implementation="int" default-value="0">${lastModGranularityMs}</staleMillis>
<target implementation="java.lang.String" default-value="1.5">${maven.compiler.target}</target>
<testSource implementation="java.lang.String">${maven.compiler.testSource}</testSource>
<testTarget implementation="java.lang.String">${maven.compiler.testTarget}</testTarget>
<useIncrementalCompilation implementation="boolean" default-value="true">${maven.compiler.useIncrementalCompilation}</useIncrementalCompilation>
<verbose implementation="boolean" default-value="false">${maven.compiler.verbose}</verbose>
<mavenSession implementation="org.apache.maven.execution.MavenSession" default-value="${session}"/>
<session implementation="org.apache.maven.execution.MavenSession" default-value="${session}"/>
</configuration>
Look at the above code and find out the following 2 lines
<source implementation="java.lang.String" default-value="1.5">${maven.compiler.source}</source>
<target implementation="java.lang.String" default-value="1.5">${maven.compiler.target}</target>
Good luck.
My problem was overwriting my query string parameters with default values:
routes.MapRoute(
"apiRoute",
"api/{action}/{key}",
new { controller = "Api", action = "Prices", key = ""}
);
No matter what I plugged into query string or how only key=""
results.
Then got rid of default overwrites using UrlParameter.Optional:
routes.MapRoute(
"apiRoute",
"api/{action}/{key}",
new { controller = "Api", action = "Prices", key = UrlParameter.Optional }
);
now
prices/{key}
or
prices?key={key}
both work fine.
Check your windows-firewall feature in control panel. Outbound and inbound port should allow port 8089. (or write a new rule for this- Right hand side, actions - new rules.) it worked for me!
With ES6 you can simply do:
for(const element of Results) {
element.Active = "false";
}
A practical observation... In my NodeJS script I have the following function:
function writeToLogFile (message) {
fs.appendFile('myserverlog.txt', Date() + " " + message + "\r\n", function (err) {
if (err) throw err;
});
}
First I had only "\n" but I noticed that when I open the log file in Notepad, it shows all entries on the same line. Notepad++ on the other hand shows the entries each on their own line. After changing the code to "\r\n", even Notepad shows every entry on its own line.
SQL Server doesn't allow you to pass parameters to a procedure that you haven't defined. I think the closest you can get to this sort of design is to use optional parameters like so:
CREATE PROCEDURE GetTaskEvents
@TaskName varchar(50),
@ID int = NULL
AS
BEGIN
-- SP Logic
END;
You would need to include every possible parameter that you might use in the definition. Then you'd be free to call the procedure either way:
EXEC GetTaskEvents @TaskName = 'TESTTASK', @ID = 2;
EXEC GetTaskEvents @TaskName = 'TESTTASK'; -- @ID gets NULL here
Yes, you can reference any image from the image
element. And you can use data URIs to make the SVG self-contained. An example:
<svg xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink">
...
<image
width="100" height="100"
xlink:href="data:image/png;base64,IMAGE_DATA"
/>
...
</svg>
The svg
element attribute xmlns:xlink
declares xlink
as a namespace prefix and says where the definition is. That then allows the SVG reader to know what xlink:href
means.
The IMAGE_DATA
is where you'd add the image data as base64-encoded text. Vector graphics editors that support SVG usually have an option for saving with images embedded. Otherwise there are plenty of tools around for encoding a byte stream to and from base64.
Here's a full example from the SVG testsuite.
To deploy your application to prod environment add
"build": "vue-cli-service build --mode prod"
in your scripts in package.json file.
Open your main.js and add
Vue.config.productionTip = false;
right after your imports. Then open your cli in the project folder and run this command
npm run build
This will make a dist folder in your project directory you may upload that dist folder in your host and your website will be live
You need to explicitly ask for the content type.
Add this line:
request.ContentType = "application/json; charset=utf-8";
At the appropriate place
Combination of solutions for react
let converter = Intl.NumberFormat();
let salary = monthlySalary.replace(/,/g,'')
console.log(converter.format(salary))
this.setState({
monthlySalary: converter.format(salary)
})
}
handleOnChangeMonthlySalary(1000)```
I used this code:
ws.Range("A:A").FormulaR1C1 = "=DATEVALUE(RC[1])"
column A will be mm/dd/yyyy
RC[1] is column B, the TEXT string, eg, 01/30/12, THIS IS NOT DATE TYPE
Use a Requirements File (see link to JetBrains documentation)
In my case I needed arrow
. So, I added
arrow==0.7.0
to my projects requirements.txt
Then Intellij prompted me to add the library the first time that I wrote import arrow
in a Python script
Your question doesn't have anything to do with PHP... just CSS.
Your CSS is correct, but your browser won't typically be able to open what you have put in for a URL. At a minimum, you'll need a file:
path. It would be best to reference the file by its relative path.
When it comes to Muhammad Mehdi's answer, it is better to do:
private void salary_texbox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
Regex regex = new Regex ( "[^0-9]+" );
if(regex.IsMatch(e.Text))
{
MessageBox.Show("Error");
}
}
Because when comparing with the TextCompositionEventArgs it gets also the last character, while with the textbox.Text it does not. With textbox, the error will show after next inserted character.
function handleFileSelect(evt) {_x000D_
var files = evt.target.files;_x000D_
_x000D_
// Loop through the FileList and render image files as thumbnails._x000D_
for (var i = 0, f; f = files[i]; i++) {_x000D_
_x000D_
// Only process image files._x000D_
if (!f.type.match('image.*')) {_x000D_
continue;_x000D_
}_x000D_
_x000D_
var reader = new FileReader();_x000D_
_x000D_
// Closure to capture the file information._x000D_
reader.onload = (function(theFile) {_x000D_
return function(e) {_x000D_
// Render thumbnail._x000D_
var span = document.createElement('span');_x000D_
span.innerHTML = _x000D_
[_x000D_
'<img style="height: 75px; border: 1px solid #000; margin: 5px" src="', _x000D_
e.target.result,_x000D_
'" title="', escape(theFile.name), _x000D_
'"/>'_x000D_
].join('');_x000D_
_x000D_
document.getElementById('list').insertBefore(span, null);_x000D_
};_x000D_
})(f);_x000D_
_x000D_
// Read in the image file as a data URL._x000D_
reader.readAsDataURL(f);_x000D_
}_x000D_
}_x000D_
_x000D_
document.getElementById('files').addEventListener('change', handleFileSelect, false);
_x000D_
<input type="file" id="files" multiple />_x000D_
<output id="list"></output>
_x000D_
If you want to parse a String to a char, whereas the String object represent more than one character, you just simply use the following expression: char c = (char) Integer.parseInt(s). Where s equals the String you want to parse. Most people forget that char's represent a 16-bit number, and thus can be a part of any numerical expression :)
Its advantages are that it simplifies the usage of WebSockets as you described in #2, and probably more importantly it provides fail-overs to other protocols in the event that WebSockets are not supported on the browser or server. I would avoid using WebSockets directly unless you are very familiar with what environments they don't work and you are capable of working around those limitations.
This is a good read on both WebSockets and Socket.IO.
Does your find
have the -mmin
option? That can let you test the number of mins since last modification:
find $LOCATION -name $REQUIRED_FILES -type f -mmin +360 -delete
Or maybe look at using tmpwatch
to do the same job. phjr also recommended tmpreaper
in the comments.
The Collections.sort
method can sort a List
using a Comparator
you pass. That Comparator
can be implemented using the Comparator.comparing
method where you can pass a method reference as the necessary Function
. Fortunately, the actual code is much simpler and shorter than this description.
For Java 8:
Collections.sort(list, comparing(ClassName::getName));
or
Collections.sort(list, comparing(ClassName::getName).reversed());
Another way is
Collections.sort(list, comparing(ClassName::getName, Comparator.nullsLast(Comparator.naturalOrder())));
I have create a eclipse plugin to create activity in one click .
Just download the Plugin from https://docs.google.com/file/d/0B63U_IjxUP_GMkdYZzc1Y3lEM1U/edit?usp=sharing
Paste the plugin in the dropins folder in Eclipse and restart eclipse
For more details please see my blog
http://shareatramachandran.blogspot.in/2013/06/android-activity-plugin-for-eclispe.html
Need your comment on this if it was helpful...
Try with this:
const { jasper } = this.state; //Gets the object from state
jasper.name = 'A new name'; //do whatever you want with the object
this.setState({jasper}); //Replace the object in state
Try adding this
package.json
devDependencies: {
//...
"@react-native-community/cli-debugger-ui": "4.7.0"
}
Terminate everything.
npm install
npx react-native start
npx react-native run-android
Reference: https://github.com/react-native-community/cli/issues/1081#issuecomment-614223917
In my case, it worked like that:
from BeautifulSoup import BeautifulSoup as bs
url="http://blabla.com"
soup = bs(urllib.urlopen(url))
for link in soup.findAll('a'):
print link.string
Hope it helps!
Position Independent Code means that the generated machine code is not dependent on being located at a specific address in order to work.
E.g. jumps would be generated as relative rather than absolute.
Pseudo-assembly:
PIC: This would work whether the code was at address 100 or 1000
100: COMPARE REG1, REG2
101: JUMP_IF_EQUAL CURRENT+10
...
111: NOP
Non-PIC: This will only work if the code is at address 100
100: COMPARE REG1, REG2
101: JUMP_IF_EQUAL 111
...
111: NOP
EDIT: In response to comment.
If your code is compiled with -fPIC, it's suitable for inclusion in a library - the library must be able to be relocated from its preferred location in memory to another address, there could be another already loaded library at the address your library prefers.
I think you are getting confused about what the a:active
CSS selector does. This will only change the colour of your link when you click it (and only for the duration of the click i.e. how long your mouse button stays down). What you need to do is introduce a new class e.g. .selected
into your CSS and when you select a link, update the selected menu item with new class e.g.
<div class="menuBar">
<ul>
<li class="selected"><a href="index.php">HOME</a></li>
<li><a href="two.php">PORTFOLIO</a></li>
....
</ul>
</div>
// specific CSS for your menu
div.menuBar li.selected a { color: #FF0000; }
// more general CSS
li.selected a { color: #FF0000; }
You will need to update your template page to take in a selectedPage
parameter.
First check if the request object have the 'is_private' key parameter. Most of the case's this MultiValueDictKeyError occurred for missing key in the dictionary-like request object. Because dictionary is an unordered key, value pair “associative memories” or “associative arrays”
In another word. request.GET or request.POST is a dictionary-like object containing all request parameters. This is specific to Django.
The method get() returns a value for the given key if key is in the dictionary. If key is not available then returns default value None.
You can handle this error by putting :
is_private = request.POST.get('is_private', False);
If you're looking for a document-level key event handling, then binding it during componentDidMount
is the best way (as shown by Brad Colthurst's codepen example):
class ActionPanel extends React.Component {
constructor(props){
super(props);
this.escFunction = this.escFunction.bind(this);
}
escFunction(event){
if(event.keyCode === 27) {
//Do whatever when esc is pressed
}
}
componentDidMount(){
document.addEventListener("keydown", this.escFunction, false);
}
componentWillUnmount(){
document.removeEventListener("keydown", this.escFunction, false);
}
render(){
return (
<input/>
)
}
}
Note that you should make sure to remove the key event listener on unmount to prevent potential errors and memory leaks.
EDIT: If you are using hooks, you can use this useEffect
structure to produce a similar effect:
const ActionPanel = (props) => {
const escFunction = useCallback((event) => {
if(event.keyCode === 27) {
//Do whatever when esc is pressed
}
}, []);
useEffect(() => {
document.addEventListener("keydown", escFunction, false);
return () => {
document.removeEventListener("keydown", escFunction, false);
};
}, []);
return (
<input />
)
};
"".join([i for i in my_list])
This should work just like you asked!
for me replace doesn't work... try this code:
str = str.split(""").join('"');
Another option is to ask IDEA to behave like eclipse with eclipse shortcut keys. You can use all eclipse shortcuts by enabling this.
Here are the steps:
1- With IDEA open, press Control + `. Following options will be popped up.
2- Select Keymap. You will see another pop-up. Select Eclipse there.
3- Now press Ctrl + Shift + O
. You are done!
The key to debugging situations like these is to run the subquery/inline view on its' own to see what the output is:
SELECT TOP 1
dm.marker_value,
dum.profile_id
FROM DPS_USR_MARKERS dum (NOLOCK)
JOIN DPS_MARKERS dm (NOLOCK) ON dm.marker_id= dum.marker_id
AND dm.marker_key = 'moneyBackGuaranteeLength'
ORDER BY dm.creation_date
Running that, you would see that the profile_id
value didn't match the u.id
value of u162231993
, which would explain why any mbg
references would return null
(thanks to the left join; you wouldn't get anything if it were an inner join).
You've coded yourself into a corner using TOP
, because now you have to tweak the query if you want to run it for other users. A better approach would be:
SELECT u.id,
x.marker_value
FROM DPS_USER u
LEFT JOIN (SELECT dum.profile_id,
dm.marker_value,
dm.creation_date
FROM DPS_USR_MARKERS dum (NOLOCK)
JOIN DPS_MARKERS dm (NOLOCK) ON dm.marker_id= dum.marker_id
AND dm.marker_key = 'moneyBackGuaranteeLength'
) x ON x.profile_id = u.id
JOIN (SELECT dum.profile_id,
MAX(dm.creation_date) 'max_create_date'
FROM DPS_USR_MARKERS dum (NOLOCK)
JOIN DPS_MARKERS dm (NOLOCK) ON dm.marker_id= dum.marker_id
AND dm.marker_key = 'moneyBackGuaranteeLength'
GROUP BY dum.profile_id) y ON y.profile_id = x.profile_id
AND y.max_create_date = x.creation_date
WHERE u.id = 'u162231993'
With that, you can change the id
value in the where
clause to check records for any user in the system.
Have a look and see if the the JDK is at:
Library/Java/JavaVirtualMachines/ Or /System/Library/Java/JavaVirtualMachines/
Check this earlier SO post: JDK on OSX 10.7 Lion
There's always the Bogobogosort (Bogoception!). It performs Bogosort on increasingly large subsets of the list, and then starts all over again if the list is ever not sorted.
for (int n=1; n<sizeof(list); ++n) {
while (!isInOrder(list, 0, n)) {
shuffle(list, 0, n);
}
if (!isInOrder(list, 0, n+1)) { n=0; }
}
echo "Hello MY name is SUJIT " | sed 's/./\L&/g'
Output:
hello my name is sujit
If you don't have a .gitignore file. You can create a new one by
touch .gitignore
And you can exclude a folder by entering the below command in the .gitignore file
/folderName
push this file into your git repository so that when a new person clone your project he don't have to add the same again
Firstly you need to install a SSH server in the images you wish to ssh-into. You can use a base image for all your container with the ssh server installed.
Then you only have to run each container mapping the ssh port (default 22) to one to the host's ports (Remote Server in your image), using -p <hostPort>:<containerPort>
. i.e:
docker run -p 52022:22 container1
docker run -p 53022:22 container2
Then, if ports 52022 and 53022 of host's are accessible from outside, you can directly ssh to the containers using the ip of the host (Remote Server) specifying the port in ssh with -p <port>
. I.e.:
ssh -p 52022 myuser@RemoteServer
--> SSH to container1
ssh -p 53022 myuser@RemoteServer
--> SSH to container2
I think you're confused about types here. You'll only get that result if you're multiplying a string. Start the interpreter and try this:
>>> print "1" * 9
111111111
>>> print 1 * 9
9
>>> print int("1") * 9
9
So make sure the first operand is an integer (and not a string), and it will work.
You can do this by using cors. cors will handle your CORS response
var cors = require('cors')
app.use(cors());
Check https://github.com/linways/table-to-excel. Its a wrapper for exceljs/exceljs to export html tables to xlsx.
TableToExcel.convert(document.getElementById("simpleTable1"));
_x000D_
<script src="https://cdn.jsdelivr.net/gh/linways/[email protected]/dist/tableToExcel.js"></script>_x000D_
<table id="simpleTable1" data-cols-width="70,15,10">_x000D_
<tbody>_x000D_
<tr>_x000D_
<td class="header" colspan="5" data-f-sz="25" data-f-color="FFFFAA00" data-a-h="center" data-a-v="middle" data-f-underline="true">_x000D_
Sample Excel_x000D_
</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td colspan="5" data-f-italic="true" data-a-h="center" data-f-name="Arial" data-a-v="top">_x000D_
Italic and horizontal center in Arial_x000D_
</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<th data-a-text-rotation="90">Col 1 (number)</th>_x000D_
<th data-a-text-rotation="vertical">Col 2</th>_x000D_
<th data-a-wrap="true">Wrapped Text</th>_x000D_
<th data-a-text-rotation="-45">Col 4 (date)</th>_x000D_
<th data-a-text-rotation="-90">Col 5</th>_x000D_
</tr>_x000D_
<tr>_x000D_
<td rowspan="1" data-t="n">1</td>_x000D_
<td rowspan="1" data-b-b-s="thick" data-b-l-s="thick" data-b-r-s="thick">_x000D_
ABC1_x000D_
</td>_x000D_
<td rowspan="1" data-f-strike="true">Striked Text</td>_x000D_
<td data-t="d">05-20-2018</td>_x000D_
<td data-t="n" data-num-fmt="$ 0.00">2210.00</td>_x000D_
</tr>_x000D_
_x000D_
<tr>_x000D_
<td rowspan="2" data-t="n">2</td>_x000D_
<td rowspan="2" data-fill-color="FFFF0000" data-f-color="FFFFFFFF">_x000D_
ABC 2_x000D_
</td>_x000D_
<td rowspan="2" data-a-indent="3">Merged cell</td>_x000D_
<td data-t="d">05-21-2018</td>_x000D_
<td data-t="n" data-b-a-s="dashed" data-num-fmt="$ 0.00">230.00</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td data-t="d">05-22-2018</td>_x000D_
_x000D_
<td data-t="n" data-num-fmt="$ 0.00">2493.00</td>_x000D_
</tr>_x000D_
_x000D_
<tr>_x000D_
<td colspan="4" align="right" data-f-bold="true" data-a-h="right" data-hyperlink="https://google.com">_x000D_
<b><a href="https://google.com">Hyperlink</a></b>_x000D_
</td>_x000D_
<td colspan="1" align="right" data-t="n" data-f-bold="true" data-num-fmt="$ 0.00">_x000D_
<b>4933.00</b>_x000D_
</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td colspan="4" align="right" data-f-bold="true" data-a-rtl="true">_x000D_
?????_x000D_
</td>_x000D_
<td colspan="1" align="right" data-t="n" data-f-bold="true" data-num-fmt="$ 0.00">_x000D_
<b>2009.00</b>_x000D_
</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td data-b-a-s="dashed" data-b-a-c="FFFF0000">All borders</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td data-t="b">true</td>_x000D_
<td data-t="b">false</td>_x000D_
<td data-t="b">1</td>_x000D_
<td data-t="b">0</td>_x000D_
<td data-error="#VALUE!">Value Error</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td data-b-t-s="thick" data-b-l-s="thick" data-b-b-s="thick" data-b-r-s="thick" data-b-t-c="FF00FF00" data-b-l-c="FF00FF00" data-b-b-c="FF00FF00" data-b-r-c="FF00FF00">_x000D_
All borders separately_x000D_
</td>_x000D_
</tr>_x000D_
<tr data-exclude="true">_x000D_
<td>Excluded row</td>_x000D_
<td>Something</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Included Cell</td>_x000D_
<td data-exclude="true">Excluded Cell</td>_x000D_
<td>Included Cell</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>
_x000D_
This creates valid xlsx on the client side. Also supports some basic styling. Check https://codepen.io/rohithb/pen/YdjVbb for a working example.
public static JSONArray RemoveJSONArray( JSONArray jarray,int pos) {
JSONArray Njarray=new JSONArray();
try{
for(int i=0;i<jarray.length();i++){
if(i!=pos)
Njarray.put(jarray.get(i));
}
}catch (Exception e){e.printStackTrace();}
return Njarray;
}
Version I am using
Update 5th May 2012
Jeff Smith has blogged showing, what I believe is the superior method to get CSV output from SQL Developer. Jeff's method is shown as Method 1 below:
Method 1
Add the comment /*csv*/
to your SQL query and run the query as a script (using F5 or the 2nd execution button on the worksheet toolbar)
That's it.
Method 2
Run a query
Right click and select unload.
Update. In Sql Developer Version 3.0.04 unload has been changed to export Thanks to Janis Peisenieks for pointing this out
Revised screen shot for SQL Developer Version 3.0.04
From the format drop down select CSV
And follow the rest of the on screen instructions.
Try the following to support basic html tags including ul ol li tags. Create a Tag handler as shown below
import org.xml.sax.XMLReader;
import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.Html;
import android.text.Html.TagHandler;
import android.util.Log;
public class MyTagHandler implements TagHandler {
boolean first= true;
String parent=null;
int index=1;
@Override
public void handleTag(boolean opening, String tag, Editable output,
XMLReader xmlReader) {
if(tag.equals("ul")) parent="ul";
else if(tag.equals("ol")) parent="ol";
if(tag.equals("li")){
if(parent.equals("ul")){
if(first){
output.append("\n\t•");
first= false;
}else{
first = true;
}
}
else{
if(first){
output.append("\n\t"+index+". ");
first= false;
index++;
}else{
first = true;
}
}
}
}
}
Set the text on Activity as shown below
@SuppressWarnings("deprecation")
public void init(){
try {
TextView help = (TextView) findViewById(R.id.help);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
help.setText(Html.fromHtml(getString(R.string.help_html),Html.FROM_HTML_MODE_LEGACY, null, new MyTagHandler()));
} else {
help.setText(Html.fromHtml(getString(R.string.help_html), null, new MyTagHandler()));
}
} catch (Exception e) {
e.printStackTrace();
}
}
And html text on resource string files as
<![CDATA[ ...raw html data ...]] >
Open .iml file. Look for keyword 'NewModuleRootManager'. Check if attribute 'inherit-compiler-output' is set to true or not. If not set to true.
Like this :
component name="NewModuleRootManager" inherit-compiler-output="true">
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/test" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/spec" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/app" isTestSource="false" />
This way can be helpful if you want to comment some Django Template format Code.
{#% include 'file.html' %#}
(Right Way)
Following code still executes if commented with HTML Comment.
<!-- {% include 'file.html' %} -->
(Wrong Way)
You're missing FIELDS TERMINATED BY ','
and it's assuming you're delimiting by tabs by default.
Datatype: array_name:datatype[]=[];
Example string: users:string[]=[];
For array of objects:
Objecttype: object_name:objecttype[]=[{}];
Example user: Users:user[]=[{}];
And if in some cases it's coming undefined in binding, make sure to initialize it on Oninit()
.
I feel your frustration.
Android is crazy fragmented, and the the sheer amount of different examples on the web when searching is not helping.
That said, I just completed a sample partly based on mustafasevgi sample, partly built from several other stackoverflow answers, I try to achieve this functionality, in the most simplistic way possible, I feel this is close to the goal.
(Mind you, code should be easy to read and tweak, so it does not fit your json object perfectly, but should be super easy to edit, to fit any scenario)
protected class yourDataTask extends AsyncTask<Void, Void, JSONObject>
{
@Override
protected JSONObject doInBackground(Void... params)
{
String str="http://your.domain.here/yourSubMethod";
URLConnection urlConn = null;
BufferedReader bufferedReader = null;
try
{
URL url = new URL(str);
urlConn = url.openConnection();
bufferedReader = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
StringBuffer stringBuffer = new StringBuffer();
String line;
while ((line = bufferedReader.readLine()) != null)
{
stringBuffer.append(line);
}
return new JSONObject(stringBuffer.toString());
}
catch(Exception ex)
{
Log.e("App", "yourDataTask", ex);
return null;
}
finally
{
if(bufferedReader != null)
{
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
@Override
protected void onPostExecute(JSONObject response)
{
if(response != null)
{
try {
Log.e("App", "Success: " + response.getString("yourJsonElement") );
} catch (JSONException ex) {
Log.e("App", "Failure", ex);
}
}
}
}
This would be the json object it is targeted towards.
{
"yourJsonElement":"Hi, I'm a string",
"anotherElement":"Ohh, why didn't you pick me"
}
It is working on my end, hope this is helpful to someone else out there.
The command git config --list
will list the settings. There you should also find user.name
and user.email
.
Tensorflow also implemented functions for resizing/padding images tf.image.pad tf.pad.
padded_image = tf.image.pad_to_bounding_box(image, top_padding, left_padding, target_height, target_width)
padded_image = tf.pad(image, paddings, "CONSTANT")
These functions work just like other input-pipeline features of tensorflow and will work much better for machine learning applications.
'below is from
'http://www.zipcodeworld.com/samples/distance.vbnet.html
Public Function distance(ByVal lat1 As Double, ByVal lon1 As Double, _
ByVal lat2 As Double, ByVal lon2 As Double, _
Optional ByVal unit As Char = "M"c) As Double
Dim theta As Double = lon1 - lon2
Dim dist As Double = Math.Sin(deg2rad(lat1)) * Math.Sin(deg2rad(lat2)) + _
Math.Cos(deg2rad(lat1)) * Math.Cos(deg2rad(lat2)) * _
Math.Cos(deg2rad(theta))
dist = Math.Acos(dist)
dist = rad2deg(dist)
dist = dist * 60 * 1.1515
If unit = "K" Then
dist = dist * 1.609344
ElseIf unit = "N" Then
dist = dist * 0.8684
End If
Return dist
End Function
Public Function Haversine(ByVal lat1 As Double, ByVal lon1 As Double, _
ByVal lat2 As Double, ByVal lon2 As Double, _
Optional ByVal unit As Char = "M"c) As Double
Dim R As Double = 6371 'earth radius in km
Dim dLat As Double
Dim dLon As Double
Dim a As Double
Dim c As Double
Dim d As Double
dLat = deg2rad(lat2 - lat1)
dLon = deg2rad((lon2 - lon1))
a = Math.Sin(dLat / 2) * Math.Sin(dLat / 2) + Math.Cos(deg2rad(lat1)) * _
Math.Cos(deg2rad(lat2)) * Math.Sin(dLon / 2) * Math.Sin(dLon / 2)
c = 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1 - a))
d = R * c
Select Case unit.ToString.ToUpper
Case "M"c
d = d * 0.62137119
Case "N"c
d = d * 0.5399568
End Select
Return d
End Function
Private Function deg2rad(ByVal deg As Double) As Double
Return (deg * Math.PI / 180.0)
End Function
Private Function rad2deg(ByVal rad As Double) As Double
Return rad / Math.PI * 180.0
End Function
Why is everyone complicating this?
The only problem is Math.atan2( x , y)
The corret answer is Math.atan2( y, x)
All they did was mix the variable order for Atan2 causing it to reverse the degree of rotation.
All you had to do was look up the syntax https://www.google.com/amp/s/www.geeksforgeeks.org/java-lang-math-atan2-java/amp/
set "PathName=X:\Web Content Mgmt\Completed Filtering\2013_Folder"
set "comd=dir /b /s *.zip"
cd /d "%PathName%"
%comd%
http://en.wikipedia.org/wiki/Post/Redirect/Get
The most common way to implement this pattern in ASP.Net is to use Response.Redirect(Request.RawUrl)
Consider the differences between Redirect and Transfer. Transfer really isn't telling the browser to forward to a clear form, it's simply returning a cleared form. That may or may not be what you want.
Response.Redirect() does not a waste round trip. If you post to a script that clears the form by Server.Transfer() and reload you will be asked to repost by most browsers since the last action was a HTTP POST. This may cause your users to unintentionally repeat some action, eg. place a second order which will have to be voided later.
On OSX using the current Chrome build (2/20/2020, 79.0.3945.130), you can:
Click on the 'i' info icon on the left side of address bar.
Click Site Settings
Scroll down to Insecure content
Change it from Blocked (Default)
to Allow
Reload the page and try your action again.
Super easy if model hasn't been created yet:
First, copy your image file to the upload path (assumed = 'path/' in following snippet).
Second, use something like:
class Layout(models.Model):
image = models.ImageField('img', upload_to='path/')
layout = Layout()
layout.image = "path/image.png"
layout.save()
tested and working in django 1.4, it might work also for an existing model.
Missing ;
after var_dump($row)
I just wrote a blog post on saving an object's data to Binary, XML, or Json. It sounds like you probably want to use Binary serialization, but perhaps you want the files to be edited outside of your app, in which case XML or Json might be better. Here are the functions to do it in the various formats. See my blog post for more details.
/// <summary>
/// Writes the given object instance to a binary file.
/// <para>Object type (and all child types) must be decorated with the [Serializable] attribute.</para>
/// <para>To prevent a variable from being serialized, decorate it with the [NonSerialized] attribute; cannot be applied to properties.</para>
/// </summary>
/// <typeparam name="T">The type of object being written to the XML file.</typeparam>
/// <param name="filePath">The file path to write the object instance to.</param>
/// <param name="objectToWrite">The object instance to write to the XML file.</param>
/// <param name="append">If false the file will be overwritten if it already exists. If true the contents will be appended to the file.</param>
public static void WriteToBinaryFile<T>(string filePath, T objectToWrite, bool append = false)
{
using (Stream stream = File.Open(filePath, append ? FileMode.Append : FileMode.Create))
{
var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
binaryFormatter.Serialize(stream, objectToWrite);
}
}
/// <summary>
/// Reads an object instance from a binary file.
/// </summary>
/// <typeparam name="T">The type of object to read from the XML.</typeparam>
/// <param name="filePath">The file path to read the object instance from.</param>
/// <returns>Returns a new instance of the object read from the binary file.</returns>
public static T ReadFromBinaryFile<T>(string filePath)
{
using (Stream stream = File.Open(filePath, FileMode.Open))
{
var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
return (T)binaryFormatter.Deserialize(stream);
}
}
Requires the System.Xml assembly to be included in your project.
/// <summary>
/// Writes the given object instance to an XML file.
/// <para>Only Public properties and variables will be written to the file. These can be any type though, even other classes.</para>
/// <para>If there are public properties/variables that you do not want written to the file, decorate them with the [XmlIgnore] attribute.</para>
/// <para>Object type must have a parameterless constructor.</para>
/// </summary>
/// <typeparam name="T">The type of object being written to the file.</typeparam>
/// <param name="filePath">The file path to write the object instance to.</param>
/// <param name="objectToWrite">The object instance to write to the file.</param>
/// <param name="append">If false the file will be overwritten if it already exists. If true the contents will be appended to the file.</param>
public static void WriteToXmlFile<T>(string filePath, T objectToWrite, bool append = false) where T : new()
{
TextWriter writer = null;
try
{
var serializer = new XmlSerializer(typeof(T));
writer = new StreamWriter(filePath, append);
serializer.Serialize(writer, objectToWrite);
}
finally
{
if (writer != null)
writer.Close();
}
}
/// <summary>
/// Reads an object instance from an XML file.
/// <para>Object type must have a parameterless constructor.</para>
/// </summary>
/// <typeparam name="T">The type of object to read from the file.</typeparam>
/// <param name="filePath">The file path to read the object instance from.</param>
/// <returns>Returns a new instance of the object read from the XML file.</returns>
public static T ReadFromXmlFile<T>(string filePath) where T : new()
{
TextReader reader = null;
try
{
var serializer = new XmlSerializer(typeof(T));
reader = new StreamReader(filePath);
return (T)serializer.Deserialize(reader);
}
finally
{
if (reader != null)
reader.Close();
}
}
You must include a reference to Newtonsoft.Json assembly, which can be obtained from the Json.NET NuGet Package.
/// <summary>
/// Writes the given object instance to a Json file.
/// <para>Object type must have a parameterless constructor.</para>
/// <para>Only Public properties and variables will be written to the file. These can be any type though, even other classes.</para>
/// <para>If there are public properties/variables that you do not want written to the file, decorate them with the [JsonIgnore] attribute.</para>
/// </summary>
/// <typeparam name="T">The type of object being written to the file.</typeparam>
/// <param name="filePath">The file path to write the object instance to.</param>
/// <param name="objectToWrite">The object instance to write to the file.</param>
/// <param name="append">If false the file will be overwritten if it already exists. If true the contents will be appended to the file.</param>
public static void WriteToJsonFile<T>(string filePath, T objectToWrite, bool append = false) where T : new()
{
TextWriter writer = null;
try
{
var contentsToWriteToFile = JsonConvert.SerializeObject(objectToWrite);
writer = new StreamWriter(filePath, append);
writer.Write(contentsToWriteToFile);
}
finally
{
if (writer != null)
writer.Close();
}
}
/// <summary>
/// Reads an object instance from an Json file.
/// <para>Object type must have a parameterless constructor.</para>
/// </summary>
/// <typeparam name="T">The type of object to read from the file.</typeparam>
/// <param name="filePath">The file path to read the object instance from.</param>
/// <returns>Returns a new instance of the object read from the Json file.</returns>
public static T ReadFromJsonFile<T>(string filePath) where T : new()
{
TextReader reader = null;
try
{
reader = new StreamReader(filePath);
var fileContents = reader.ReadToEnd();
return JsonConvert.DeserializeObject<T>(fileContents);
}
finally
{
if (reader != null)
reader.Close();
}
}
// To save the characterSheet variable contents to a file.
WriteToBinaryFile<CharacterSheet>("C:\CharacterSheet.pfcsheet", characterSheet);
// To load the file contents back into a variable.
CharacterSheet characterSheet = ReadFromBinaryFile<CharacterSheet>("C:\CharacterSheet.pfcsheet");
In javascript almost everything is an object, null
and undefined
are exception.
Instances of Array
is an object. so you can set property of an array, for the same reason,you can't set property of a undefined, because its NOT an object
Here is my take on it, seems like most peoples solutions don't check if the item exists and it removes random values if it does not exist.
First check if the element exists by looking for it's index. If it does exist, remove it by its index using the splice method
elementPosition = array.indexOf(value);
if(elementPosition != -1) {
array.splice(elementPosition, 1);
}
<input type="button" value="submit" style="height: 100px; width: 100px; left: 250; top: 250;">
Use this with your requirements.
Use the java.lang.Math class, and specifically for absolute value and square root:, the abs()
and sqrt()
methods.
Additional details to the previous answer:
While React's setState
is asynchronous (both classes and hooks), and it's tempting to use that fact to explain the observed behavior, it is not the reason why it happens.
TLDR: The reason is a closure scope around an immutable const
value.
read the value in render function (not inside nested functions):
useEffect(() => { setMovies(result) }, [])
console.log(movies)
add the variable into dependencies (and use the react-hooks/exhaustive-deps eslint rule):
useEffect(() => { setMovies(result) }, [])
useEffect(() => { console.log(movies) }, [movies])
use a mutable reference (when the above is not possible):
const moviesRef = useRef(initialValue)
useEffect(() => {
moviesRef.current = result
console.log(moviesRef.current)
}, [])
If async was the only reason, it would be possible to await setState()
.
However, both props
and state
are assumed to be unchanging during 1 render.
Treat
this.state
as if it were immutable.
With hooks, this assumption is enhanced by using constant values with the const
keyword:
const [state, setState] = useState('initial')
The value might be different between 2 renders, but remains a constant inside the render itself and inside any closures (functions that live longer even after render is finished, e.g. useEffect
, event handlers, inside any Promise or setTimeout).
Consider following fake, but synchronous, React-like implementation:
// sync implementation:
let internalState
let renderAgain
const setState = (updateFn) => {
internalState = updateFn(internalState)
renderAgain()
}
const useState = (defaultState) => {
if (!internalState) {
internalState = defaultState
}
return [internalState, setState]
}
const render = (component, node) => {
const {html, handleClick} = component()
node.innerHTML = html
renderAgain = () => render(component, node)
return handleClick
}
// test:
const MyComponent = () => {
const [x, setX] = useState(1)
console.log('in render:', x) // ?
const handleClick = () => {
setX(current => current + 1)
console.log('in handler/effect/Promise/setTimeout:', x) // ? NOT updated
}
return {
html: `<button>${x}</button>`,
handleClick
}
}
const triggerClick = render(MyComponent, document.getElementById('root'))
triggerClick()
triggerClick()
triggerClick()
_x000D_
<div id="root"></div>
_x000D_
I've the same problem, and the below solution exactly work for me....!
Edit eclipse.ini
file and remove these two lines:
--launcher.library
.%%..\eclipse\plugins\eclipse\plugins\org.eclipse.equinox.launcher.win32.win32.x86_1.1.200.v20120522-1813
Make sure make a separate copy of this file before any changing...:)
Here is the process that is more simple and works both for the formats dd/mm/yyyy and dd-mm-yyyy. This is working great for me:
<?php
$birthday = '26/04/1994';
$dob = strtotime(str_replace("/", "-", $birthday));
$tdate = time();
echo date('Y', $tdate) - date('Y', $dob);
?>
And if you care about your time zone just add above date_default_timezone_set("Asia/Dhaka");
change the zone with yours.
Even if the question states Java, most of the answers have digressed. So I thought I would do the same :)
We have been using Adobe AIR for the last 5 years and it is truly cross-platform and provides native-like performance with the same code base (at least 99% of our code is the same). Adobe AIR got some bad press at the beginning during the 'beta' period (slow, no GPU, Flash 'dead' etc.) But now, it's amazing what you can do with it. Not to mention the wealth of open source libs out there.
With the same code base you can push your app onto:
Why bother with Java or Objective-C ?
The only common platform not covered is Window Phone. But that's coming soon too.
For an Android App, if you're using Genymotion you can toggle the menu by pressing CMD + m
, but you may have to enable it in the menu by doing this.
CMD + m
click on debug in chromeSELECT * FROM pg_stat_activity WHERE datname = 'dbname' and state = 'active';
Since pg_stat_activity
contains connection statistics of all databases having any state, either idle
or active
, database name and connection state should be included in the query to get the desired output.
use IDLE Editor {You may already have it} it has interactive shell for python and it will show you execution and result.
You need to use the doubleValue()
method to get the double value from a BigDecimal object.
BigDecimal bd; // the value you get
double d = bd.doubleValue(); // The double you want
On IE7, IE8, and IE9 just go to Settings->Internet Options->Security->Custom Level and change security settings under "Miscellaneous" set "Access data sources across domains" to Enable.
The tool that richardtz suggests is excellent.
Another one that is amazing and comes with a 30 day free trial is Araxis Merge. This one does a 3 way merge and is much more feature complete than winmerge, but it is a commercial product.
You might also like to check out Scott Hanselman's developer tool list, which mentions a couple more in addition to winmerge
I had a similar issue when working on Database restore operation on MS SQL Server 2012.
However, for my own scenario, I just needed to see the progress of the DATABASE RESTORE operation in the script window
All I had to do was add the STATS option to the script:
USE master;
GO
ALTER DATABASE mydb SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
GO
RESTORE DATABASE mydb
FROM DISK = 'C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\Backup\my_db_21-08-2020.bak'
WITH REPLACE,
STATS = 10,
RESTART,
MOVE 'my_db' TO 'C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\DATA\my_db.mdf',
MOVE 'my_db_log' TO 'C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\DATA\mydb_log.ldf'
GO
ALTER DATABASE mydb SET MULTI_USER;
GO
And then I switched to the Messages tab of the Script window to see the progress of the DATABASE RESTORE operation:
If you want to get more information after the DATABASE RESTORE operation you can use this command suggested by eythort:
SELECT command, percent_complete, start_time FROM sys.dm_exec_requests where command = 'RESTORE DATABASE'
That's all.
I hope this helps
this is to further clarify JD Isaaks answer ...
The problem you run into often is that you are using php to output html from many different php sources, and those sources are often, for whatever reason, outputting via different ways.
Sometimes you have literal html content that you want to directly output to the browser; other times the output is being dynamically created (server-side).
The dynamic content is always(?) going to be a string. Now you have to combine this stringified dynamic html with any literal, direct-to-display html ... into one meaningful html node structure.
This usually forces the developer to wrap all that direct-to-display content into a string (as JD Isaak was discussing) so that it can be properly delivered/inserted in conjunction with the dynamic html ... even though you don't really want it wrapped.
But by using ob_## methods you can avoid that string-wrapping mess. The literal content is, instead, output to the buffer. Then in one easy step the entire contents of the buffer (all your literal html), is concatenated into your dynamic-html string.
(My example shows literal html being output to the buffer, which is then added to a html-string ... look also at JD Isaaks example to see string-wrapping-of-html).
<?php // parent.php
//---------------------------------
$lvs_html = "" ;
$lvs_html .= "<div>html</div>" ;
$lvs_html .= gf_component_assembler__without_ob( ) ;
$lvs_html .= "<div>more html</div>" ;
$lvs_html .= "----<br/>" ;
$lvs_html .= "<div>html</div>" ;
$lvs_html .= gf_component_assembler__with_ob( ) ;
$lvs_html .= "<div>more html</div>" ;
echo $lvs_html ;
// 02 - component contents
// html
// 01 - component header
// 03 - component footer
// more html
// ----
// html
// 01 - component header
// 02 - component contents
// 03 - component footer
// more html
//---------------------------------
function gf_component_assembler__without_ob( )
{
$lvs_html = "<div>01 - component header</div>" ; // <table ><tr>" ;
include( "component_contents.php" ) ;
$lvs_html .= "<div>03 - component footer</div>" ; // </tr></table>" ;
return $lvs_html ;
} ;
//---------------------------------
function gf_component_assembler__with_ob( )
{
$lvs_html = "<div>01 - component header</div>" ; // <table ><tr>" ;
ob_start();
include( "component_contents.php" ) ;
$lvs_html .= ob_get_clean();
$lvs_html .= "<div>03 - component footer</div>" ; // </tr></table>" ;
return $lvs_html ;
} ;
//---------------------------------
?>
<!-- component_contents.php -->
<div>
02 - component contents
</div>
Those classes are common extension points for Java UI designs. First off, realize that they don't necessarily have much to do with each other directly, so trying to find a relationship between them might be counterproductive.
JApplet - A base class that let's you write code that will run within the context of a browser, like for an interactive web page. This is cool and all but it brings limitations which is the price for it playing nice in the real world. Normally JApplet is used when you want to have your own UI in a web page. I've always wondered why people don't take advantage of applets to store state for a session so no database or cookies are needed.
JComponent - A base class for objects which intend to interact with Swing.
JFrame - Used to represent the stuff a window should have. This includes borders (resizeable y/n?), titlebar (App name or other message), controls (minimize/maximize allowed?), and event handlers for various system events like 'window close' (permit app to exit yet?).
JPanel - Generic class used to gather other elements together. This is more important with working with the visual layout or one of the provided layout managers e.g. gridbaglayout, etc. For example, you have a textbox that is bigger then the area you have reserved. Put the textbox in a scrolling pane and put that pane into a JPanel. Then when you place the JPanel, it will be more manageable in terms of layout.
That's correct. You can find more about it in the Oracle guide on varargs.
Here's an example:
void foo(String... args) {
for (String arg : args) {
System.out.println(arg);
}
}
which can be called as
foo("foo"); // Single arg.
foo("foo", "bar"); // Multiple args.
foo("foo", "bar", "lol"); // Don't matter how many!
foo(new String[] { "foo", "bar" }); // Arrays are also accepted.
foo(); // And even no args.
To change into another directory use WORKDIR. All the RUN, CMD and ENTRYPOINT commands after WORKDIR will be executed from that directory.
RUN git clone XYZ
WORKDIR "/XYZ"
RUN make
"FetchType.LAZY
" will only fire for primary table. If in your code you call any other method that has a parent table dependency then it will fire query to get that table information. (FIRES MULTIPLE SELECT)
"FetchType.EAGER
" will create join of all table including relevant parent tables directly. (USES JOIN
)
When to Use:
Suppose you compulsorily need to use dependant parent table informartion then choose FetchType.EAGER
.
If you only need information for certain records then use FetchType.LAZY
.
Remember, FetchType.LAZY
needs an active db session factory at the place in your code where if you choose to retrieve parent table information.
E.g. for LAZY
:
.. Place fetched from db from your dao loayer
.. only place table information retrieved
.. some code
.. getCity() method called... Here db request will be fired to get city table info
The process for timing out an operations is described in the documentation for signal.
The basic idea is to use signal handlers to set an alarm for some time interval and raise an exception once that timer expires.
Note that this will only work on UNIX.
Here's an implementation that creates a decorator (save the following code as timeout.py
).
from functools import wraps
import errno
import os
import signal
class TimeoutError(Exception):
pass
def timeout(seconds=10, error_message=os.strerror(errno.ETIME)):
def decorator(func):
def _handle_timeout(signum, frame):
raise TimeoutError(error_message)
def wrapper(*args, **kwargs):
signal.signal(signal.SIGALRM, _handle_timeout)
signal.alarm(seconds)
try:
result = func(*args, **kwargs)
finally:
signal.alarm(0)
return result
return wraps(func)(wrapper)
return decorator
This creates a decorator called @timeout
that can be applied to any long running functions.
So, in your application code, you can use the decorator like so:
from timeout import timeout
# Timeout a long running function with the default expiry of 10 seconds.
@timeout
def long_running_function1():
...
# Timeout after 5 seconds
@timeout(5)
def long_running_function2():
...
# Timeout after 30 seconds, with the error "Connection timed out"
@timeout(30, os.strerror(errno.ETIMEDOUT))
def long_running_function3():
...
Volatile means other threads can edit that particular variable. So the compiler allows access to them.
http://www.javamex.com/tutorials/synchronization_volatile.shtml
Transient means that when you serialize an object, it will return its default value on de-serialization
I wrote a concise little method yesterday that also returns the number of decimal places without having to rely on any string splits or cultures which is ideal:
public int GetDecimalPlaces(decimal decimalNumber) { //
try {
// PRESERVE:BEGIN
int decimalPlaces = 1;
decimal powers = 10.0m;
if (decimalNumber > 0.0m) {
while ((decimalNumber * powers) % 1 != 0.0m) {
powers *= 10.0m;
++decimalPlaces;
}
}
return decimalPlaces;
input{
text-align:center;
}
is all you need.
Working example in FF6. This method doesn't seem to be cross-browser compatible.
Your previous CSS was attempting to center the text of an input element which had a class of "placeholder".
Since the expiration time is zero (the third argument, the first false
) the cookie is a session cookie, which will expire when the current session ends. (See the setcookie
reference).
Therefore it doesn't need to be saved.
Here's a bash script I use, works on OSX 10.11.3.
#!/bin/bash
PLUGINS=$(cordova plugin list | awk '{print $1}')
for PLUGIN in $PLUGINS; do
cordova plugin rm $PLUGIN --save && cordova plugin add $PLUGIN --save
done
This may help if there are conflicts, per shan's comment. The difference is the addition of the --force
flag when removing.
#!/bin/bash
PLUGINS=$(cordova plugin list | awk '{print $1}')
for PLUGIN in $PLUGINS; do
cordova plugin rm $PLUGIN --force --save && cordova plugin add $PLUGIN --save
done
So, based on the 'button in header' solution, here is a clean and minimalist implementation:
Here is the code:
@interface MyTableViewController ()
@property (nonatomic, strong) NSMutableIndexSet *collapsedSections;
@end
...
@implementation MyTableViewController
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (!self)
return;
self.collapsedSections = [NSMutableIndexSet indexSet];
return self;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// if section is collapsed
if ([self.collapsedSections containsIndex:section])
return 0;
// if section is expanded
#warning incomplete implementation
return [super tableView:tableView numberOfRowsInSection:section];
}
- (IBAction)toggleSectionHeader:(UIView *)sender
{
UITableView *tableView = self.tableView;
NSInteger section = sender.tag;
MyTableViewHeaderFooterView *headerView = (MyTableViewHeaderFooterView *)[self tableView:tableView viewForHeaderInSection:section];
if ([self.collapsedSections containsIndex:section])
{
// section is collapsed
headerView.button.selected = YES;
[self.collapsedSections removeIndex:section];
}
else
{
// section is expanded
headerView.button.selected = NO;
[self.collapsedSections addIndex:section];
}
[tableView beginUpdates];
[tableView reloadSections:[NSIndexSet indexSetWithIndex:section] withRowAnimation:UITableViewRowAnimationAutomatic];
[tableView endUpdates];
}
@end
Usually direct queries should not be used in case of linked server because it heavily use temp database of SQL server. At first step data is retrieved into temp DB then filtering occur. There are many threads about this. It is better to use open OPENQUERY because it passes SQL to the source linked server and then it return filtered results e.g.
SELECT *
FROM OPENQUERY(Linked_Server_Name , 'select * from TableName where ID = 500')
For VB.lovers the VB.NET equivalent of Luke Quinane's code (thanks Luke!)
Imports System
Imports System.Net
Imports System.Runtime.InteropServices
Imports System.ComponentModel
Public Class NetworkConnection
Implements IDisposable
Private _networkName As String
Public Sub New(networkName As String, credentials As NetworkCredential)
_networkName = networkName
Dim netResource = New NetResource() With {
.Scope = ResourceScope.GlobalNetwork,
.ResourceType = ResourceType.Disk,
.DisplayType = ResourceDisplaytype.Share,
.RemoteName = networkName
}
Dim userName = If(String.IsNullOrEmpty(credentials.Domain), credentials.UserName, String.Format("{0}\{1}", credentials.Domain, credentials.UserName))
Dim result = WNetAddConnection2(NetResource, credentials.Password, userName, 0)
If result <> 0 Then
Throw New Win32Exception(result, "Error connecting to remote share")
End If
End Sub
Protected Overrides Sub Finalize()
Try
Dispose (False)
Finally
MyBase.Finalize()
End Try
End Sub
Public Sub Dispose() Implements IDisposable.Dispose
Dispose (True)
GC.SuppressFinalize (Me)
End Sub
Protected Overridable Sub Dispose(disposing As Boolean)
WNetCancelConnection2(_networkName, 0, True)
End Sub
<DllImport("mpr.dll")> _
Private Shared Function WNetAddConnection2(netResource As NetResource, password As String, username As String, flags As Integer) As Integer
End Function
<DllImport("mpr.dll")> _
Private Shared Function WNetCancelConnection2(name As String, flags As Integer, force As Boolean) As Integer
End Function
End Class
<StructLayout(LayoutKind.Sequential)> _
Public Class NetResource
Public Scope As ResourceScope
Public ResourceType As ResourceType
Public DisplayType As ResourceDisplaytype
Public Usage As Integer
Public LocalName As String
Public RemoteName As String
Public Comment As String
Public Provider As String
End Class
Public Enum ResourceScope As Integer
Connected = 1
GlobalNetwork
Remembered
Recent
Context
End Enum
Public Enum ResourceType As Integer
Any = 0
Disk = 1
Print = 2
Reserved = 8
End Enum
Public Enum ResourceDisplaytype As Integer
Generic = &H0
Domain = &H1
Server = &H2
Share = &H3
File = &H4
Group = &H5
Network = &H6
Root = &H7
Shareadmin = &H8
Directory = &H9
Tree = &HA
Ndscontainer = &HB
End Enum
After reading your question, I would say, generate special token to do request required. This token will live in specific time (lets say in one day).
Here is an example from to generate authentication token:
(day * 10) + (month * 100) + (year (last 2 digits) * 1000)
for example: 3 June 2011
(3 * 10) + (6 * 100) + (11 * 1000) =
30 + 600 + 11000 = 11630
then concatenate with user password, example "my4wesomeP4ssword!"
11630my4wesomeP4ssword!
Then do MD5 of that string:
05a9d022d621b64096160683f3afe804
When do you call a request, always use this token,
https://mywebservice.com/?token=05a9d022d621b64096160683f3afe804&op=getdata
This token is always unique everyday, so I guess this kind of protection is more than sufficient to always protect ur service.
Hope helps
:)
Here is a slightly simpler version that I found. It reads the entire file in one go and only requires a single using
directive.
byte[] ComputeHash(string filePath)
{
using (var md5 = MD5.Create())
{
return md5.ComputeHash(File.ReadAllBytes(filePath));
}
}
How do I create a new column with Groupby().Sum()?
There are two ways - one straightforward and the other slightly more interesting.
GroupBy.transform()
with 'sum'
@Ed Chum's answer can be simplified, a bit. Call DataFrame.groupby
rather than Series.groupby
. This results in simpler syntax.
# The setup.
df[['Date', 'Data3']]
Date Data3
0 2015-05-08 5
1 2015-05-07 8
2 2015-05-06 6
3 2015-05-05 1
4 2015-05-08 50
5 2015-05-07 100
6 2015-05-06 60
7 2015-05-05 120
df.groupby('Date')['Data3'].transform('sum')
0 55
1 108
2 66
3 121
4 55
5 108
6 66
7 121
Name: Data3, dtype: int64
It's a tad faster,
df2 = pd.concat([df] * 12345)
%timeit df2['Data3'].groupby(df['Date']).transform('sum')
%timeit df2.groupby('Date')['Data3'].transform('sum')
10.4 ms ± 367 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
8.58 ms ± 559 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
GroupBy.sum()
+ Series.map()
I stumbled upon an interesting idiosyncrasy in the API. From what I tell, you can reproduce this on any major version over 0.20 (I tested this on 0.23 and 0.24). It seems like you consistently can shave off a few milliseconds of the time taken by transform
if you instead use a direct function of GroupBy
and broadcast it using map
:
df.Date.map(df.groupby('Date')['Data3'].sum())
0 55
1 108
2 66
3 121
4 55
5 108
6 66
7 121
Name: Date, dtype: int64
Compare with
df.groupby('Date')['Data3'].transform('sum')
0 55
1 108
2 66
3 121
4 55
5 108
6 66
7 121
Name: Data3, dtype: int64
My tests show that map
is a bit faster if you can afford to use the direct GroupBy
function (such as mean
, min
, max
, first
, etc). It is more or less faster for most general situations upto around ~200 thousand records. After that, the performance really depends on the data.
(Left: v0.23, Right: v0.24)
Nice alternative to know, and better if you have smaller frames with smaller numbers of groups. . . but I would recommend transform
as a first choice. Thought this was worth sharing anyway.
Benchmarking code, for reference:
import perfplot
perfplot.show(
setup=lambda n: pd.DataFrame({'A': np.random.choice(n//10, n), 'B': np.ones(n)}),
kernels=[
lambda df: df.groupby('A')['B'].transform('sum'),
lambda df: df.A.map(df.groupby('A')['B'].sum()),
],
labels=['GroupBy.transform', 'GroupBy.sum + map'],
n_range=[2**k for k in range(5, 20)],
xlabel='N',
logy=True,
logx=True
)
There are many errors in your code, for example you are not really calling your deck by just typing deck
in your Shuffle
method. You can only call it by typing theCard.deck
I have changed your shuffle method:
public void Shuffle(){
for (int i = 0; i < theCard.deck.length; i++) {
int index = (int)(Math.random()*theCard.deck.length );
int temp = theCard.deck[i];
theCard.deck[i] = theCard.deck[index];
theCard.deck[index] = temp;
remainingCards--;
}
}
Also, as it is said you have structural problem. You should name classes as you understand in real life, for example, when you say card, it is only one card, when you say deck it is supposed to be 52+2 cards. In this way your code would be more understandable.
if you are working on dynamic permissions and any permission like ACCESS_FINE_LOCATION,ACCESS_COARSE_LOCATION giving error "cannot resolve method PERMISSION_NAME" in this case write you code with permission name and then rebuild your project this will regenerate the manifest(Manifest.permission) file.
Instead of git pull
also try git pull origin master
I changed password, and the first command gave error:
$ git pull
remote: Invalid username or password.
fatal: Authentication failed for ...
After git pull origin master
, it asked for password and seemed to update itself
Straightforward way:
char digits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
char aChar = digits[i];
Safer way:
char aChar = '0' + i;
Generic way:
itoa(i, ...)
Handy way:
sprintf(myString, "%d", i)
C++ way: (taken from Dave18 answer)
std::ostringstream oss;
oss << 6;
Boss way:
Joe, write me an int to char converter
Studboss way:
char aChar = '6';
Joe's way:
char aChar = '6'; //int i = 6;
Nasa's way:
//Waiting for reply from satellite...
Alien's way: '9'
//Greetings.
God's way:
Bruh I built this
Peter Pan's way:
char aChar;
switch (i)
{
case 0:
aChar = '0';
break;
case 1:
aChar = '1';
break;
case 2:
aChar = '2';
break;
case 3:
aChar = '3';
break;
case 4:
aChar = '4';
break;
case 5:
aChar = '5';
break;
case 6:
aChar = '6';
break;
case 7:
aChar = '7';
break;
case 8:
aChar = '8';
break;
case 9:
aChar = '9';
break;
default:
aChar = '?';
break;
}
Santa Claus's way:
//Wait till Christmas!
sleep(457347347);
Gravity's way:
//What
'6' (Jersey) Mikes'™ way:
//
SO way:
Guys, how do I avoid reading beginner's guide to C++?
My way:
or the highway.
Comment: I've added Handy way and C++ way (to have a complete collection) and I'm saving this as a wiki.
Edit: satisfied?
You can also Try This
-- DECLARE field because your table type may be text
DECLARE @mmRxClaim nvarchar(MAX)
-- Getting Value from table
SELECT top (1) @mmRxClaim = mRxClaim FROM RxClaim WHERE rxclaimid_PK =362
-- Main String Value
SELECT @mmRxClaim AS MainStringValue
-- Count Multiple Character for this number of space will be number of character
SELECT LEN(@mmRxClaim) - LEN(REPLACE(@mmRxClaim, 'GS', ' ')) AS CountMultipleCharacter
-- Count Single Character for this number of space will be one
SELECT LEN(@mmRxClaim) - LEN(REPLACE(@mmRxClaim, 'G', '')) AS CountSingleCharacter
Output:
If data frame fits in a driver memory and you want to save to local files system you can convert Spark DataFrame to local Pandas DataFrame using toPandas
method and then simply use to_csv
:
df.toPandas().to_csv('mycsv.csv')
Otherwise you can use spark-csv:
Spark 1.3
df.save('mycsv.csv', 'com.databricks.spark.csv')
Spark 1.4+
df.write.format('com.databricks.spark.csv').save('mycsv.csv')
In Spark 2.0+ you can use csv
data source directly:
df.write.csv('mycsv.csv')
rem This is the command line version
cscript "C:\Users\guest\Desktop\123\MyScript.vbs"
OR
rem This is the windowed version
wscript "C:\Users\guest\Desktop\123\MyScript.vbs"
You can also add the option //e:vbscript
to make sure the scripting engine will recognize your script as a vbscript.
Windows/DOS batch files doesn't require escaping \
like *nix.
You can still use "C:\Users\guest\Desktop\123\MyScript.vbs"
, but this requires the user has *.vbs
associated to wscript
.
Though you already have an accepted answer, I figured I'd add this for anyone else interested in a different solution-
An implementation could be as follows:
import csv
with open('C:/mypath/to/csvfile.csv', 'r') as f:
d_reader = csv.DictReader(f)
#get fieldnames from DictReader object and store in list
headers = d_reader.fieldnames
for line in d_reader:
#print value in MyCol1 for each row
print(line['MyCol1'])
In the above, d_reader.fieldnames returns a list of your headers (assuming the headers are in the top row). Which allows...
>>> print(headers)
['MyCol1', 'MyCol2', 'MyCol3']
If your headers are in, say the 2nd row (with the very top row being row 1), you could do as follows:
import csv
with open('C:/mypath/to/csvfile.csv', 'r') as f:
#you can eat the first line before creating DictReader.
#if no "fieldnames" param is passed into
#DictReader object upon creation, DictReader
#will read the upper-most line as the headers
f.readline()
d_reader = csv.DictReader(f)
headers = d_reader.fieldnames
for line in d_reader:
#print value in MyCol1 for each row
print(line['MyCol1'])
window.location.href = 'URL';
is the standard implementation for changing the current window's location.
public void Each<T>(IEnumerable<T> items, Action<T> action)
{
foreach (var item in items)
action(item);
}
... and call it thusly:
Each(myList, i => Console.WriteLine(i));
Also check if all dirs which you wrote in the my.ini
exists.
My problem was that tmpdir
doeesn`t exist so MySQL daemon falls with error 1067.
[mysqld]
port= 3306
tmpdir = "C:/tmp"
In this case C:/tmp
must exists.
If you've got a cell filled with spaces or blanks, you can use:
=Len(Trim(A2)) = 0
if the cell you were testing was A2
I would probably use set
in the following manner :
set(l).issuperset(set(['a','b']))
or the other way round :
set(['a','b']).issubset(set(l))
I find it a bit more readable, but it may be over-kill. Sets are particularly useful to compute union/intersection/differences between collections, but it may not be the best option in this situation ...
If you're working with an x64 server, keep in mind that there are different ODBC settings for x86 and x64 applications. The "Data Sources (ODBC)" tool in the Administrative Tools list takes you to the x64 version. To view/edit the x86 ODBC settings, you'll need to run that version of the tool manually:
%windir%\SysWOW64\odbcad32.exe (%windir% is usually C:\Windows)
When your app runs as x64, it will use the x64 data sources, and when it runs as x86, it will use those data sources instead.
In the hypothetical situation where you could perform a potentially expensive non-const operation on an object, returning by const-value prevents you from accidentally calling this operation on a temporary. Imagine that +
returned a non-const value, and you could write:
(a + b).expensive();
In the age of C++11, however, it is strongly advised to return values as non-const so that you can take full advantage of rvalue references, which only make sense on non-constant rvalues.
In summary, there is a rationale for this practice, but it is essentially obsolete.
Neither, because both are quite verbose for a very simple task. You can just do:
let result = ({
1: 'One',
2: 'Two',
3: 'Three'
})[opt] ?? 'Default' // opt can be 1, 2, 3 or anything (default)
This, of course, also works with strings, a mix of both or without a default case:
let result = ({
'first': 'One',
'second': 'Two',
3: 'Three'
})[opt] // opt can be 'first', 'second' or 3
It works by creating an object where the options/cases are the keys and the results are the values. By putting the option into the brackets you access the value of the key that matches the expression via the bracket notation.
This returns undefined
if the expression inside the brackets is not a valid key. We can detect this undefined-case by using the nullish coalescing operator ??
and return a default value.
console.log('Using a valid case:', ({
1: 'One',
2: 'Two',
3: 'Three'
})[1] ?? 'Default')
console.log('Using an invalid case/defaulting:', ({
1: 'One',
2: 'Two',
3: 'Three'
})[7] ?? 'Default')
_x000D_
.as-console-wrapper {max-height: 100% !important;top: 0;}
_x000D_
When using any form of Ajax, detailed documentation for the format of responses received from the CGI server seems to be lacking on the Web. Some entries here point out that newlines in returned text or json data must be escaped to prevent infinite loops (hangs) in JSON conversion (possibly created by throwing an uncaught exception), whether done automatically by jQuery or manually using Javascript system or library JSON parsing calls.
In each case where programmers post this problem, inadequate solutions are presented (most often replacing \n by \\n on the sending side) and the matter is dropped. Their inadequacy is revealed when passing string values that accidentally embed control escape sequences, such as Windows pathnames. An example is "C:\Chris\Roberts.php", which contains the control characters ^c and ^r, which can cause JSON conversion of the string {"file":"C:\Chris\Roberts.php"} to loop forever. One way of generating such values is deliberately to attempt to pass PHP warning and error messages from server to client, a reasonable idea.
By definition, Ajax uses HTTP connections behind the scenes. Such connections pass data using GET and POST, both of which require encoding sent data to avoid incorrect syntax, including control characters.
This gives enough of a hint to construct what seems to be a solution (it needs more testing): to use rawurlencode on the PHP (sending) side to encode the data, and unescape on the Javascript (receiving) side to decode the data. In some cases, you will apply these to entire text strings, in other cases you will apply them only to values inside JSON.
If this idea turns out to be correct, simple examples can be constructed to help programmers at all levels solve this problem once and for all.