Java only knows about the platform it is currently running on, so it can only give you a platform-dependent output on that platform (using bw.newLine()
) . The fact that you open it on a windows system means that you either have to convert the file before using it (using something you have written, or using a program like unix2dos), or you have to output the file with windows format carriage returns in it originally in your Java program. So if you know the file will always be opened on a windows machine, you will have to output
bw.write(rs.getString(1)==null? "":rs.getString(1));
bw.write("\r\n");
It's worth noting that you aren't going to be able to output a file that will look correct on both platforms if it is just plain text you are using, you may want to consider using html if it is an email, or xml if it is data. Alternatively, you may need some kind of client that reads the data and then formats it for the platform that the viewer is using.
Set is just an interface. In order to retain order, you have to use a specific implementation of that interface and the sub-interface SortedSet, for example TreeSet or LinkedHashSet. You can wrap your Set this way:
Set myOrderedSet = new LinkedHashSet(mySet);
Based on the title of this question, I came here wanting to convert a String into an array of substrings divided by some delimiter. I will add that answer here for others who may have the same question.
This makes an array of words by splitting the string at every space:
String str = "string to string array conversion in java";
String delimiter = " ";
String strArray[] = str.split(delimiter);
This creates the following array:
// [string, to, string, array, conversion, in, java]
Tested in Java 8
HTML tag is just opening or closing entity. For example:
<p>
and </p>
are called HTML tags
HTML element encompasses opening tag, closing tag, content (optional for content-less tags) Eg:
<p>This is the content</p>
: This complete thing is called a HTML element
For elements with dynamic width it's possible to use transform: translateX(-100%);
to counter the horizontal percentage value. This leads to two possible solutions:
Transition from:
transform: translateX(0);
to
transform: translateX(calc(100vw - 100%));
#viewportPendulum {_x000D_
position: fixed;_x000D_
left: 0;_x000D_
top: 0;_x000D_
animation: 2s ease-in-out infinite alternate swingViewport;_x000D_
/* just for styling purposes */_x000D_
background: #c70039;_x000D_
padding: 1rem;_x000D_
color: #fff;_x000D_
font-family: sans-serif;_x000D_
}_x000D_
_x000D_
@keyframes swingViewport {_x000D_
from {_x000D_
transform: translateX(0);_x000D_
}_x000D_
to {_x000D_
transform: translateX(calc(100vw - 100%));_x000D_
}_x000D_
}
_x000D_
<div id="viewportPendulum">Viewport</div>
_x000D_
Transition from:
transform: translateX(0);
left: 0;
to
left: 100%;
transform: translateX(-100%);
#parentPendulum {_x000D_
position: relative;_x000D_
display: inline-block;_x000D_
animation: 2s ease-in-out infinite alternate swingParent;_x000D_
/* just for styling purposes */_x000D_
background: #c70039;_x000D_
padding: 1rem;_x000D_
color: #fff;_x000D_
font-family: sans-serif;_x000D_
}_x000D_
_x000D_
@keyframes swingParent {_x000D_
from {_x000D_
transform: translateX(0);_x000D_
left: 0;_x000D_
}_x000D_
to {_x000D_
left: 100%;_x000D_
transform: translateX(-100%);_x000D_
}_x000D_
}_x000D_
_x000D_
.wrapper {_x000D_
padding: 2rem 0;_x000D_
margin: 2rem 15%;_x000D_
background: #eee;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
<div id="parentPendulum">Parent</div>_x000D_
</div>
_x000D_
Note: This approach can easily be extended to work for vertical positioning. Visit example here.
Select2 for Bootstrap 3 native plugin
https://fk.github.io/select2-bootstrap-css/index.html
this plugin uses select2 jquery plugin
nuget
PM> Install-Package Select2-Bootstrap
Right. The function you pass to getLocations() won't get called until the data is available, so returning "country" before it's been set isn't going to help you.
The way you need to do this is to have the function that you pass to geocoder.getLocations() actually do whatever it is you wanted done with the returned values.
Something like this:
function reverseGeocode(latitude,longitude){
var geocoder = new GClientGeocoder();
var latlng = new GLatLng(latitude, longitude);
geocoder.getLocations(latlng, function(addresses) {
var address = addresses.Placemark[0].address;
var country = addresses.Placemark[0].AddressDetails.Country.CountryName;
var countrycode = addresses.Placemark[0].AddressDetails.Country.CountryNameCode;
var locality = addresses.Placemark[0].AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName;
do_something_with_address(address, country, countrycode, locality);
});
}
function do_something_with_address(address, country, countrycode, locality) {
if (country==="USA") {
alert("USA A-OK!"); // or whatever
}
}
If you might want to do something different every time you get the location, then pass the function as an additional parameter to reverseGeocode:
function reverseGeocode(latitude,longitude, callback){
// Function contents the same as above, then
callback(address, country, countrycode, locality);
}
reverseGeocode(latitude, longitude, do_something_with_address);
If this looks a little messy, then you could take a look at something like the Deferred feature in Dojo, which makes the chaining between functions a little clearer.
You can execute below code
SELECT Time FROM [TableName] where DATEPART(YYYY,[Time])='2018' and DATEPART(MM,[Time])='06' and DATEPART(DD,[Time])='14
Just try to send a session variable when you press log in. And on the welcome page, first check whether that session is empty like this in the page load or in the Init Event:
if(Session["UserID"] == null || Session["UserID"] == "")
{
Response.Redirect("Login.aspx");
}
PHP runs on the server and Javascript runs on the client, so you can't set a PHP variable to equal a Javascript variable without sending the value to the server. You can, however, set a Javascript variable to equal a PHP variable:
<script type="text/javascript">
var foo = '<?php echo $foo ?>';
</script>
To send a Javascript value to PHP you'd need to use AJAX. With jQuery, it would look something like this (most basic example possible):
var variableToSend = 'foo';
$.post('file.php', {variable: variableToSend});
On your server, you would need to receive the variable sent in the post:
$variable = $_POST['variable'];
I'd make a comment, but I don't have the required reputation. A small improvement to Maxim Kuzmin's otherwise very good answer to make it more efficient:
const options = [_x000D_
{ name: 'One', assigned: true }, _x000D_
{ name: 'Two', assigned: false }, _x000D_
{ name: 'Three', assigned: true }, _x000D_
];_x000D_
_x000D_
const filtered = options_x000D_
.reduce((result, { name, assigned }) => assigned ? result.concat(name) : result, []);_x000D_
_x000D_
console.log(filtered);
_x000D_
Explanation
Instead of spreading the entire result over and over for each iteration, we only append to the array, and only when there's actually a value to insert.
First, give all your links a unique id and make a css class called active:
<ul>
<li><a id="link1" href="#/...">link 1</a></li>
<li><a id="link2" href="#/...">link 2</a></li>
</ul>
CSS:
.active {
font-weight: bold;
}
Jquery version:
function setActiveLink(setActive){
if ($("a").hasClass('active'))
$("a").removeClass('active');
if (setActive)
$("#"+setActive).addClass('active');
}
$(function() {
$("a").click(function() {
setActiveLink(this.id);
});
});
Vanilla javascript version:
In order to prevent selecting too many links with document.querySelectorAll
, give the parent element an id called menuLinks. Add an onClick handler on the links.
<ul id="menuLinks">
<li><a id="link1" href="#/..." onClick="setActiveLink(this.id);">link 1</a></li>
<li><a id="link2" href="#/..." onClick="setActiveLink(this.id);">link 2</a></li>
</ul>
Code:
function setActiveLink(setActive){
var links = document.querySelectorAll("#menuLinks a");
Array.prototype.map.call(links, function(e) {
e.className = "";
if (e.id == setActive)
e.className = "active";
})
}
Look at Process.Start and Process.StartInfo
To create an image with width equals screen width, and height proportionally set according to aspect ratio, do the following.
Glide.with(context).load(url).asBitmap().into(new SimpleTarget<Bitmap>() {
@Override
public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
// creating the image that maintain aspect ratio with width of image is set to screenwidth.
int width = imageView.getMeasuredWidth();
int diw = resource.getWidth();
if (diw > 0) {
int height = 0;
height = width * resource.getHeight() / diw;
resource = Bitmap.createScaledBitmap(resource, width, height, false);
}
imageView.setImageBitmap(resource);
}
});
Hope this helps.
Make the (LinearLayout) android:layout_width="match_parent"
and the TextView's android:layout_gravity="right"
array1.NonIntersect(array2);
Nonintersect such operator is not present in Linq you should do
except -> union -> except
a.except(b).union(b.Except(a));
A warning by which the compiler indicates that it cannot ensure type safety. The term "unchecked" warning is misleading. It does not mean that the warning is unchecked in any way. The term "unchecked" refers to the fact that the compiler and the runtime system do not have enough type information to perform all type checks that would be necessary to ensure type safety. In this sense, certain operations are "unchecked".
The most common source of "unchecked" warnings is the use of raw types. "unchecked" warnings are issued when an object is accessed through a raw type variable, because the raw type does not provide enough type information to perform all necessary type checks.
Example (of unchecked warning in conjunction with raw types):
TreeSet set = new TreeSet();
set.add("abc"); // unchecked warning
set.remove("abc");
warning: [unchecked] unchecked call to add(E) as a member of the raw type java.util.TreeSet
set.add("abc");
^
When the add method is invoked the compiler does not know whether it is safe to add a String object to the collection. If the TreeSet is a collection that contains String s (or a supertype thereof), then it would be safe. But from the type information provided by the raw type TreeSet the compiler cannot tell. Hence the call is potentially unsafe and an "unchecked" warning is issued.
"unchecked" warnings are also reported when the compiler finds a cast whose target type is either a parameterized type or a type parameter.
Example (of an unchecked warning in conjunction with a cast to a parameterized type or type variable):
class Wrapper<T> {
private T wrapped ;
public Wrapper (T arg) {wrapped = arg;}
...
public Wrapper <T> clone() {
Wrapper<T> clon = null;
try {
clon = (Wrapper<T>) super.clone(); // unchecked warning
} catch (CloneNotSupportedException e) {
throw new InternalError();
}
try {
Class<?> clzz = this.wrapped.getClass();
Method meth = clzz.getMethod("clone", new Class[0]);
Object dupl = meth.invoke(this.wrapped, new Object[0]);
clon.wrapped = (T) dupl; // unchecked warning
} catch (Exception e) {}
return clon;
}
}
warning: [unchecked] unchecked cast
found : java.lang.Object
required: Wrapper <T>
clon = ( Wrapper <T>)super.clone();
^
warning: [unchecked] unchecked cast
found : java.lang.Object
required: T
clon. wrapped = (T)dupl;
A cast whose target type is either a (concrete or bounded wildcard) parameterized type or a type parameter is unsafe, if a dynamic type check at runtime is involved. At runtime, only the type erasure is available, not the exact static type that is visible in the source code. As a result, the runtime part of the cast is performed based on the type erasure, not on the exact static type.
In the example, the cast to Wrapper would check whether the object returned from super.clone is a Wrapper , not whether it is a wrapper with a particular type of members. Similarly, the casts to the type parameter T are cast to type Object at runtime, and probably optimized away altogether. Due to type erasure, the runtime system is unable to perform more useful type checks at runtime.
In a way, the source code is misleading, because it suggests that a cast to the respective target type is performed, while in fact the dynamic part of the cast only checks against the type erasure of the target type. The "unchecked" warning is issued to draw the programmer's attention to this mismatch between the static and dynamic aspect of the cast.
Please refer: What is an "unchecked" warning?
I would go with Option 3 but multiple NON NULLABLE bit columns instead of one. IsMale (1=Yes / 0=No) IsFemale (1=Yes / 0=No)
if requried: IsUnknownGender (1=Yes / 0=No) and so on...
This makes for easy reading of the definitions, easy extensibility, easy programmability, no possibility of using values outside the domain and no requirement of a second lookup table+FK or CHECK constraints to lock down the values.
EDIT: Correction, you do need at least one constraint to ensure the set flags are valid.
The modern Git should able to detect remote branches and create a local one on checkout.
However if you did a shallow clone (e.g. with --depth 1
), try the following commands to correct it:
git config remote.origin.fetch '+refs/heads/*:refs/remotes/origin/*'
git fetch --all
and try to checkout out the branch again.
Alternatively try to unshallow your clone, e.g. git fetch --unshallow
and try again.
See also: How to fetch all remote branches?
create procedure <procedure_name>(p_cur out sys_refcursor) as begin open p_cur for select * from <table_name> end;
In Swift 5, you can utilize dot notation for a bit quicker syntax:
myButton.titleLabel?.font = .systemFont(ofSize: 14, weight: .medium)
Otherwise, you'll use:
myButton.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: .medium)
Easiest way I find is to:
Right click project
Debug as -> Maven build ...
In the goals field put -Dmaven.surefire.debug test
In the parameters put a new parameter called forkCount with a value of 0 (previously was forkMode=never but it is deprecated and doesn't work anymore)
Set your breakpoints down and run this configuration and it should hit the breakpoint.
As an addon to Dima V's answer this is what I did to make this work for me.
// First declare the window global outside the class
declare let window: any;
// Inside the required class method
let globVarName = window.globVarName;
The only way to control the size of stack within process is start a new Thread
. But you can also control by creating a self-calling sub Java process with the -Xss
parameter.
public class TT {
private static int level = 0;
public static long fact(int n) {
level++;
return n < 2 ? n : n * fact(n - 1);
}
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread(null, null, "TT", 1000000) {
@Override
public void run() {
try {
level = 0;
System.out.println(fact(1 << 15));
} catch (StackOverflowError e) {
System.err.println("true recursion level was " + level);
System.err.println("reported recursion level was "
+ e.getStackTrace().length);
}
}
};
t.start();
t.join();
try {
level = 0;
System.out.println(fact(1 << 15));
} catch (StackOverflowError e) {
System.err.println("true recursion level was " + level);
System.err.println("reported recursion level was "
+ e.getStackTrace().length);
}
}
}
I had the same problem on Windows. I used to read the file in scala line by line with
Source.fromFile(path).getLines()
Now I read it as a whole with
import org.apache.commons.io.FileUtils._
// encoding is null for platform default
val content=readFileToString(new File(path),null.asInstanceOf[String])
which closes the file properly after reading and now
new File(path).delete
works.
I have another variant which may be useful for someone:
$('<img src="http://example.com/someresource.jpg">').load(function() {
$('#login').submit();
}).appendTo("body");
Using Android Studio 3.4.1, it no longer creates layout-land
folder. It will create a folder and put two layout files together.
A simple example of testing Tesseract OCR in C#:
public static string GetText(Bitmap imgsource)
{
var ocrtext = string.Empty;
using (var engine = new TesseractEngine(@"./tessdata", "eng", EngineMode.Default))
{
using (var img = PixConverter.ToPix(imgsource))
{
using (var page = engine.Process(img))
{
ocrtext = page.GetText();
}
}
}
return ocrtext;
}
Info: The tessdata folder must exist in the repository: bin\Debug\
For completeness, the OP does not state he is looking to do this in a browser (if he is, as has been stated, it is generally not possible)
However javascript per se does allow this; it can be done with server side javascript.
See this documentation on the Javascript File class
Edit: That link was to the Sun docs that now have been moved by Oracle.
To keep up with the times here's the node.js documentation for the FileSystem class: http://nodejs.org/docs/latest/api/fs.html
Edit(2): You can read files client side now with HTML5: http://www.html5rocks.com/en/tutorials/file/dndfiles/
Short Answer: Encrypt the link like youtube does, don't know how than ask youtube/google of how they do it. (Just in case you want to get straight into the point.)
I would like to point out to anyone that this is possible because youtube does it and if they can so can any other website and it isn't from the browser either because I tested it on a couple browsers such as microsoft edge and internet explorer and so there is a way to disable it and seen that people still say it...I tries looking for an answer because if youtube can than there has to be a way and the only way to see how they do it is if someone looked into the scripts of youtube which I am doing now. I also checked to see if it was a custom context menu as well and it isn't because the context menu is over flowing the inspect element and I mean like it is over it and I looked and it never creates a new class and also it is impossible to actually access inspect element with javascript so it can't be. You can tell when it double right-click a youtube video that it pops up the context menu for chrome. Besides...youtube wouldn't add that function in. I am doing research and looking through the source of youtube so I will be back if I find the answer...if anyone says you can't than, well they didn't do research like I have. The only way to download youtube videos is through a video download.
Okay...I did research and my research stays that you can disable it except there is no javascript to it...you have to be able to encrypt the links to the video for you to be able to disable it because I think any browser won't show it if it can't find it and when I opened a youtube video link it showed as this "blob:https://www.youtube.com/e5c4808e-297e-451f-80da-3e838caa1275" without quotes so it is encrypting it so it cannot be saved...you need to know php for that but like the answer you picked out of making it harder, youtube makes it the hardest of heavy encrypting it, you need to be an advance php programmer but if you don't know that than take the person you picked as best answer of making it hard to download it...but if you know php than heavy encrypt the video link so it only is able to be read on yours...I don't know how to explain how they do it but they did and there is a way. The way youtube Encrypts there videos is quite smart so if you want to know how to than just ask youtube/google of how they do it...hope this helps for you although you already picked a best answer. So encrypting the link is best in short terms.
Commons-net surely. :) Most open source projects use it these days.
yc
I needed something similar, the ability to click on a set of icons to indicate a choice, or a text-based choice and have that update the model (2-way-binding) with the represented value and to also a way to indicate which was selected visually. I created an AngularJS directive for it, since it needed to be flexible enough to handle any HTML element being clicked on to indicate a choice.
<ul ng-repeat="vote in votes" ...>
<li data-choice="selected" data-value="vote.id">...</li>
</ul>
It works like this:
<ScrollViewer VerticalScrollBarVisibility="Visible" HorizontalScrollBarVisibility="Disabled" Width="340" HorizontalAlignment="Left" Margin="12,0,0,0">
<StackPanel Name="stackPanel1" Width="311">
</StackPanel>
</ScrollViewer>
TextBox tb = new TextBox();
tb.TextChanged += new TextChangedEventHandler(TextBox_TextChanged);
stackPanel1.Children.Add(tb);
This should do what you want:
print tempfile.gettempdir()
For me on my Windows box, I get:
c:\temp
and on my Linux box I get:
/tmp
You can copy all enumerable own properties of an object to a new one by Object.assign(target, ...sources):
trivial_object = Object.assign({}, non_trivial_object);
so in your scenario, it should be enough to change
ret.push(i);
to
ret.push(Object.assign({}, i));
I needed to generate mongodb ids on client side.
After digging into the mongodb source code i found they generate ObjectIDs using npm bson
lib.
If ever you need only to generate an ObjectID without installing the whole mongodb / mongoose package, you can import the lighter bson
library :
const bson = require('bson');
new bson.ObjectId(); // 5cabe64dcf0d4447fa60f5e2
Note: There is also an npm project named bson-objectid
being even lighter
If you declare it like
int x;
in a header file which is then included in multiple places, you'll end up with multiple instances of x (and potentially compile or link problems).
The correct way to approach this is to have the header file say
extern int x; /* declared in foo.c */
and then in foo.c you can say
int x; /* exported in foo.h */
THen you can include your header file in as many places as you like.
Check the partition where you have installed docker. In most cases, the partition is at 100% capacity so you may need to look into that.
Since git 2.23 (August 2019) you now have a shortcut to do that: git restore --staged [filepath]
.
With this command, you could ignore a conflicted file without needing to add and remove that.
Example:
> git status
...
Unmerged paths:
(use "git add <file>..." to mark resolution)
both modified: file.ex
> git restore --staged file.ex
> git status
...
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git restore <file>..." to discard changes in working directory)
modified: file.ex
Presuming you have a .dmp file created by oracle exp then
imp help=y
will be your friend. It will lead you to
imp file=<file>.dmp show=y
to see the contents of the dump and then something like
imp scott/tiger@example file=<file>.dmp fromuser=<source> touser=<dest>
to import from one user to another. Be prepared for a long haul though if it is a complicated schema as you will need to precreate all referenced schema users, and tablespaces to make the imp work correctly
Increasing the timeout will not likely solve your issue since, as you say, the actual target web server is responding just fine.
I had this same issue and I found it had to do with not using a keep-alive on the connection. I can't actually answer why this is but, in clearing the connection header I solved this issue and the request was proxied just fine:
server {
location / {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $http_host;
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_pass http://localhost:5000;
}
}
Have a look at this posts which explains it in more detail: nginx close upstream connection after request Keep-alive header clarification http://nginx.org/en/docs/http/ngx_http_upstream_module.html#keepalive
Add System.Web.Extensions as a reference to your project
For Ref.
Works for me. try using center-block
<div class="container row text-center">
<div class="row">
<div class="span4"></div>
<div class="span4"><img class="center-block" src="logo.png" /></div>
<div class="span4"></div>
</div>
</div>
using System;
namespace ConsoleApp1
{
class Program
{
static void Main()
{
Console.WriteLine("Enter Your FirstName ");
String FirstName = Console.ReadLine();
Console.WriteLine("Enter Your LastName ");
String LastName = Console.ReadLine();
Console.ReadLine();
Console.WriteLine("Hello {0}, {1} ", FirstName, LastName);
Console.ReadLine();
}
}
}
The answer probably depends how critical it is for you to receive support and possible customization for this service.
Google can certainly do this. Look into their XML and Geocoding API's. You should be able to craft an XML message asking Google to return Map coordinates for a given address. If the address is not found (invalid), you will receive an appropriate response. Here's a useful page: http://code.google.com/apis/maps/documentation/services.html#XML_Requests
Note that Google's aim in providing the Maps API is to plot addresses on actual maps. While you can certainly use the data for other purposes, you are at the mercy of Google should one of their maps not exactly correspond to your legal or commercial address validation needs. If you paid for one of the services you mentioned, you would likely be able to receive support should certain addresses not resolve the way you expect them to.
In other words, you get what you pay for ;) . If you have the time, though, why not try implementing a Google-based solution then going from there? The API looks pretty slick, and it's free, after all.
The solution that worked for me in ASP.NET Core 3.1:
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
});
services.AddControllersWithViews();
}
and then change the following:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseCors("CorsPolicy");
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
Then program worked and error was solved.
As was stated, your reader needs to be 'step' scoped. You can accomplish this via the @Scope("step")
annotation. It should work for you if you add that annotation to your reader, like the following:
import org.springframework.batch.item.ItemReader;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component("foo-reader")
@Scope("step")
public final class MyReader implements ItemReader<MyData> {
@Override
public MyData read() throws Exception {
//...
}
@Value("#{jobParameters['fileName']}")
public void setFileName(final String name) {
//...
}
}
This scope is not available by default, but will be if you are using the batch
XML namespace. If you are not, adding the following to your Spring configuration will make the scope available, per the Spring Batch documentation:
<bean class="org.springframework.batch.core.scope.StepScope" />
it turns out that with python 2.5.2, del l[:]
is slightly slower than l[:] = []
by 1.1 usec.
$ python -mtimeit "l=list(range(1000))" "b=l[:];del b[:]"
10000 loops, best of 3: 29.8 usec per loop
$ python -mtimeit "l=list(range(1000))" "b=l[:];b[:] = []"
10000 loops, best of 3: 28.7 usec per loop
$ python -V
Python 2.5.2
As Seth stated thread safe means that a method or class instance can be used by multiple threads at the same time without any problems occuring.
Consider the following method:
private int myInt = 0;
public int AddOne()
{
int tmp = myInt;
tmp = tmp + 1;
myInt = tmp;
return tmp;
}
Now thread A
and thread B
both would like to execute AddOne()
. but A
starts first and reads the value of myInt (0)
into tmp
. Now for some reason the scheduler decides to halt thread A
and defer execution to thread B
. Thread B
now also reads the value of myInt
(still 0
) into it's own variable tmp
. Thread B
finishes the entire method, so in the end myInt = 1
. And 1
is returned. Now it's Thread A
's turn again. Thread A
continues. And adds 1
to tmp
(tmp
was 0
for thread A
). And then saves this value in myInt
. myInt
is again 1
.
So in this case the method AddOne()
was called two times, but because the method was not implemented in a thread safe way the value of myInt
is not 2
, as expected, but 1
because the second thread read the variable myInt
before the first thread finished updating it.
Creating thread safe methods is very hard in non trivial cases. And there are quite a few techniques. In Java you can mark a method as synchronized, this means that only one thread can execute that method at a given time. The other threads wait in line. This makes a method thread safe, but if there is a lot of work to be done in a method, then this wastes a lot of time. Another technique is to 'mark only a small part of a method as synchronized' by creating a lock or semaphore, and locking this small part (usually called the critical section). There are even some methods that are implemented as lockless thread safe, which means that they are built in such a way that multiple threads can race through them at the same time without ever causing problems, this can be the case when a method only executes one atomic call. Atomic calls are calls that can't be interrupted and can only be done by one thread at a time.
I believe it's in C:\Windows\System32\WindowsPowershell\v1.0\
. In order to confuse the innocent, MS kept it in a directory labeled "v1.0". Running this on Windows 7 and checking the version number via $Host.Version
(Determine installed PowerShell version) shows it's 2.0.
Another option is type $PSVersionTable
at the command prompt. If you are running v2.0, the output will be:
Name Value
---- -----
CLRVersion 2.0.50727.4927
BuildVersion 6.1.7600.16385
PSVersion 2.0
WSManStackVersion 2.0
PSCompatibleVersions {1.0, 2.0}
SerializationVersion 1.1.0.1
PSRemotingProtocolVersion 2.1
If you're running version 1.0, the variable doesn't exist and there will be no output.
Localization PowerShell version 1.0, 2.0, 3.0, 4.0:
I wrote rabbitmq-dump-queue which allows dumping messages from a RabbitMQ queue to local files and requeuing the messages in their original order.
Example usage (to dump the first 50 messages of queue incoming_1
):
rabbitmq-dump-queue -url="amqp://user:[email protected]:5672/" -queue=incoming_1 -max-messages=50 -output-dir=/tmp
The code below filters filenames starting with given substring. It could be changed to fit different needs by working on subfname substring extraction and IF statement:
echo off
rem filter all files not starting with the prefix 'dat'
setlocal enabledelayedexpansion
FOR /R your-folder-fullpath %%F IN (*.*) DO (
set fname=%%~nF
set subfname=!fname:~0,3!
IF NOT "!subfname!" == "dat" echo "%%F"
)
pause
Since I don't have a high enough reputation to comment I'll answer liang question on Feb 20 at 10:01 as an answer to the original question.
In order for the for the line labels to show you need to add plt.legend to your code. to build on the previous example above that also includes title, ylabel and xlabel:
import matplotlib.pyplot as plt
plt.plot(<X AXIS VALUES HERE>, <Y AXIS VALUES HERE>, 'line type', label='label here')
plt.plot(<X AXIS VALUES HERE>, <Y AXIS VALUES HERE>, 'line type', label='label here')
plt.title('title')
plt.ylabel('ylabel')
plt.xlabel('xlabel')
plt.legend()
plt.show()
XMLBeans will do it. Specifically the "scomp" command.
EDIT: XMLBeans has been retired, check this stackoverflow post for more info.
I was looking for a different answer for the question title, so maybe other people will be too.
To set type as an ObjectId (so you may reference author
as the author of book
, for example), you may do like:
const Book = mongoose.model('Book', {
author: {
type: mongoose.Schema.Types.ObjectId, // here you set the author ID
// from the Author colection,
// so you can reference it
required: true
},
title: {
type: String,
required: true
}
});
You do not need jQuery to do this...
function sortUnorderedList(ul, sortDescending) {
if(typeof ul == "string")
ul = document.getElementById(ul);
// Idiot-proof, remove if you want
if(!ul) {
alert("The UL object is null!");
return;
}
// Get the list items and setup an array for sorting
var lis = ul.getElementsByTagName("LI");
var vals = [];
// Populate the array
for(var i = 0, l = lis.length; i < l; i++)
vals.push(lis[i].innerHTML);
// Sort it
vals.sort();
// Sometimes you gotta DESC
if(sortDescending)
vals.reverse();
// Change the list on the page
for(var i = 0, l = lis.length; i < l; i++)
lis[i].innerHTML = vals[i];
}
Easy to use...
sortUnorderedList("ID_OF_LIST");
0 will get printed.
As in C++ true refers to 1 and false refers to 0.
In case, you want to print false instead of 0,then you have to sets the boolalpha format flag for the str stream.
When the boolalpha format flag is set, bool values are inserted/extracted by their textual representation: either true or false, instead of integral values.
#include <iostream>
int main()
{
std::cout << std::boolalpha << false << std::endl;
}
output:
false
You don't need to do special things in the form. You just build the comment correctly in the show action:
class ArticlesController < ActionController::Base
....
def show
@article = Article.find(params[:id])
@new_comment = @article.comments.build
end
....
end
and then make a form for it in the article view:
<% form_for @new_comment do |f| %>
<%= f.text_area :text %>
<%= f.submit "Post Comment" %>
<% end %>
by default, this comment will go to the create
action of CommentsController
, which you will then probably want to put redirect :back
into so you're routed back to the Article
page.
Quite simple :
For the tab control, you need to handle the _SelectedIndexChanged event:
Private Sub TabControl1_SelectedIndexChanged(sender As Object, e As System.EventArgs) _
Handles TabControl1.SelectedIndexChanged
If TabControl1.SelectedTab.Name = "TabPage1" Then
TextBox2.Focus()
End If
If TabControl1.SelectedTab.Name = "TabPage2" Then
TextBox4.Focus()
End If
Just add this method to the base class
public abstract class clsAbstractTable {
public abstract String getTAG();
public abstract void init();
}
Now every class that extends the base class (and does not want to be abstract) should provide a TAG
You could also go with BalusC's answer
If the library is included in the VS project, you can check .cproj
file, e.g.:
<ItemGroup>
<Reference Include="Microsoft.Dynamic, Version=1.1.0.20, Culture=neutral, PublicKeyToken=7f709c5b713576e1, processorArchitecture=MSIL">
...
Take a look at Shell MegaPack control set. It provides Windows Explorer like folder/file browsing with most of the features and functionality like context menus, renaming, drag-drop, icons, overlay icons, thumbnails, etc
.bashrc
is not meant to be executed but sourced. Try this instead:
. ~/.bashrc
Cheers!
public String randomString(String chars, int length) {
Random rand = new Random();
StringBuilder buf = new StringBuilder();
for (int i=0; i<length; i++) {
buf.append(chars.charAt(rand.nextInt(chars.length())));
}
return buf.toString();
}
From Python 3.0 changelog;
The StringIO and cStringIO modules are gone. Instead, import the io module and use io.StringIO or io.BytesIO for text and data respectively.
From the Python 3 email documentation it can be seen that io.StringIO
should be used instead:
from io import StringIO
from email.generator import Generator
fp = StringIO()
g = Generator(fp, mangle_from_=True, maxheaderlen=60)
g.flatten(msg)
text = fp.getvalue()
Reference: https://docs.python.org/3/library/io.html
You can use the -quit
option of find
:
find <dir> -maxdepth 1 -type d -name '*foo*' -print -quit
The window
binding refers to a built-in object provided by the browser. It represents the browser window that contains the document
. Calling its addEventListener
method registers the second argument (callback function) to be called whenever the event described by its first argument occurs.
<p>Some paragraph.</p>
<script>
window.addEventListener("click", () => {
console.log("Test");
});
</script>
Following points should be noted before select window or document to addEventListners
window
or document
but
some events like resize
, and other events related to loading
,
unloading
, and opening/closing
should all be set on the window.One of the things that you might want to try out is starting eclipse with the -clean
option. If you have chosen to have eclipse use the same workspace every time then there is nothing else you need to do after that. With that option in place the workspace should be cleaned out.
However, if you don't have a default workspace chosen, when opening up eclipse you will be prompted to choose the workspace. At this point, choose the workspace you want cleaned up.
See "How to run eclipse in clean mode" and "Keeping Eclipse running clean" for more details.
If your $result
variable is a string json like, you must use json_decode
function to parse it as an object or array:
$result = '{"Cancelled":false,"MessageID":"402f481b-c420-481f-b129-7b2d8ce7cf0a","Queued":false,"SMSError":2,"SMSIncomingMessages":null,"Sent":false,"SentDateTime":"\/Date(-62135578800000-0500)\/"}';
$json = json_decode($result, true);
print_r($json);
Array
(
[Cancelled] =>
[MessageID] => 402f481b-c420-481f-b129-7b2d8ce7cf0a
[Queued] =>
[SMSError] => 2
[SMSIncomingMessages] =>
[Sent] =>
[SentDateTime] => /Date(-62135578800000-0500)/
)
Now you can work with $json
variable as an array:
echo $json['MessageID'];
echo $json['SMSError'];
// other stuff
References:
1 - You can script sshpass's ssh
command like this:
#!/bin/bash
export SSHPASS=password
sshpass -e ssh -oBatchMode=no user@host
2 - You can script sshpass
's sftp
commandlike this:
#!/bin/bash
export SSHPASS=password
sshpass -e sftp -oBatchMode=no -b - user@host << !
put someFile
get anotherFile
bye
!
For selecting multiple image from gallery
i.putExtra(Intent.EXTRA_ALLOW_MULTIPLE,true);
An Ultimate Solution for multiple image upload with camera option also for Android Lollipop to Android 10, SDK 30.
private static final int FILECHOOSER_RESULTCODE = 1;
private ValueCallback<Uri> mUploadMessage;
private ValueCallback<Uri[]> mUploadMessages;
private Uri mCapturedImageURI = null;
Add this to OnCreate of MainActivity
mWebView.setWebChromeClient(new WebChromeClient() {
// openFileChooser for Android 3.0+
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType){
mUploadMessage = uploadMsg;
openImageChooser();
}
// For Lollipop 5.0+ Devices
public boolean onShowFileChooser(WebView mWebView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
mUploadMessages = filePathCallback;
openImageChooser();
return true;
}
// openFileChooser for Android < 3.0
public void openFileChooser(ValueCallback<Uri> uploadMsg){
openFileChooser(uploadMsg, "");
}
//openFileChooser for other Android versions
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
openFileChooser(uploadMsg, acceptType);
}
private void openImageChooser() {
try {
File imageStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "FolderName");
if (!imageStorageDir.exists()) {
imageStorageDir.mkdirs();
}
File file = new File(imageStorageDir + File.separator + "IMG_" + String.valueOf(System.currentTimeMillis()) + ".jpg");
mCapturedImageURI = Uri.fromFile(file);
final Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
i.putExtra(Intent.EXTRA_ALLOW_MULTIPLE,true);
Intent chooserIntent = Intent.createChooser(i, "Image Chooser");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Parcelable[]{captureIntent});
startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE);
} catch (Exception e) {
e.printStackTrace();
}
}
});
onActivityResult
public void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == FILECHOOSER_RESULTCODE) {
if (null == mUploadMessage && null == mUploadMessages) {
return;
}
if (null != mUploadMessage) {
handleUploadMessage(requestCode, resultCode, data);
} else if (mUploadMessages != null) {
handleUploadMessages(requestCode, resultCode, data);
}
}
}
private void handleUploadMessage(final int requestCode, final int resultCode, final Intent data) {
Uri result = null;
try {
if (resultCode != RESULT_OK) {
result = null;
} else {
// retrieve from the private variable if the intent is null
result = data == null ? mCapturedImageURI : data.getData();
}
} catch (Exception e) {
e.printStackTrace();
}
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
// code for all versions except of Lollipop
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
result = null;
try {
if (resultCode != RESULT_OK) {
result = null;
} else {
// retrieve from the private variable if the intent is null
result = data == null ? mCapturedImageURI : data.getData();
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "activity :" + e, Toast.LENGTH_LONG).show();
}
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
}
} // end of code for all versions except of Lollipop
private void handleUploadMessages(final int requestCode, final int resultCode, final Intent data) {
Uri[] results = null;
try {
if (resultCode != RESULT_OK) {
results = null;
} else {
if (data != null) {
String dataString = data.getDataString();
ClipData clipData = data.getClipData();
if (clipData != null) {
results = new Uri[clipData.getItemCount()];
for (int i = 0; i < clipData.getItemCount(); i++) {
ClipData.Item item = clipData.getItemAt(i);
results[i] = item.getUri();
}
}
if (dataString != null) {
results = new Uri[]{Uri.parse(dataString)};
}
} else {
results = new Uri[]{mCapturedImageURI};
}
}
} catch (Exception e) {
e.printStackTrace();
}
mUploadMessages.onReceiveValue(results);
mUploadMessages = null;
}
A by far easier approach is to set some layer attributes of the view on initialization:
self.layer.masksToBounds = NO;
self.layer.shadowOffset = CGSizeMake(-15, 20);
self.layer.shadowRadius = 5;
self.layer.shadowOpacity = 0.5;
You need to import QuartzCore.
#import <QuartzCore/QuartzCore.h>
It can also be done the following way.
At first rename local branch, then remote branch.
Renaming the local branch:
If logged in another branch,
git branch -m old_branch new_branch
If logged in the same branch,
git branch -m new_branch
Renaming remote branch:
git push origin :old_branch // Delete the remote branch
git push --set-upstream origin new_branch // Create a new remote branch
Run it in parallel with
cat text_file.txt | parallel --gnu "wget {}"
The order of details provided with verbose flag are as
Less details.... More details
0 < 2 < 1
Default is 1
For production environment, 2 is recommended
(function poll() {
setTimeout(function() {
//
var search = {}
search["ssn"] = "831-33-6049";
search["first"] = "Harve";
search["last"] = "Veum";
search["gender"] = "M";
search["street"] = "5017 Ottis Tunnel Apt. 176";
search["city"] = "Shamrock";
search["state"] = "OK";
search["zip"] = "74068";
search["lat"] = "35.9124";
search["long"] = "-96.578";
search["city_pop"] = "111";
search["job"] = "Higher education careers adviser";
search["dob"] = "1995-08-14";
search["acct_num"] = "11220423";
search["profile"] = "millenials.json";
search["transnum"] = "9999999";
search["transdate"] = $("#datepicker").val();
search["category"] = $("#category").val();
search["amt"] = $("#amt").val();
search["row_key"] = "831-33-6049_9999999";
$.ajax({
type : "POST",
headers : {
contentType : "application/json"
},
contentType : "application/json",
url : "/stream_more",
data : JSON.stringify(search),
dataType : 'json',
complete : poll,
cache : false,
timeout : 600000,
success : function(data) {
//
//alert('jax')
console.log("SUCCESS : ", data);
//$("#btn-search").prop("disabled", false);
// $('#feedback').html("");
for (var i = 0; i < data.length; i++) {
//
$('#feedback').prepend(
'<tr><td>' + data[i].ssn + '</td><td>'
+ data[i].transdate + '</td><td>'
+ data[i].category + '</td><td>'
+ data[i].amt + '</td><td>'
+ data[i].purch_prob + '</td><td>'
+ data[i].offer + '</td></tr>').html();
}
},
error : function(e) {
//alert("error" + e);
var json = "<h4>Ajax Response</h4><pre>" + e.responseText
+ "</pre>";
$('#feedback').html(json);
console.log("ERROR : ", e);
$("#btn-search").prop("disabled", false);
}
});
}, 3000);
})();
This is an issue of upbringing. If somewhere in your educational or professional career you spent time feeding and caring for databases (or worked closely with talented folks who did), then the fundamental tenets of entities and relationships are well-ingrained in your thought process. Among those rudiments is how/when/why to specify keys in your database (primary, foreign and perhaps alternate). It's second nature.
If, however, you've not had such a thorough or positive experience in your past with RDBMS-related endeavors, then you've likely not been exposed to such information. Or perhaps your past includes immersion in an environment that was vociferously anti-database (e.g., "those DBAs are idiots - we few, we chosen few java/c# code slingers will save the day"), in which case you might be vehemently opposed to the arcane babblings of some dweeb telling you that FKs (and the constraints they can imply) really are important if you'd just listen.
Most everyone was taught when they were kids that brushing your teeth was important. Can you get by without it? Sure, but somewhere down the line you'll have less teeth available than you could have if you had brushed after every meal. If moms and dads were responsible enough to cover database design as well as oral hygiene, we wouldn't be having this conversation. :-)
There is no simple way to do this, you basically need to subclass UITabBar and implement custom drawing to do what you want. It is quite a bit of work for the effect, but it may be worth it. I recommend filing a bug with Apple to get it added to a future iPhone SDK.
.*[^a]$
the regex above will match strings which is not ending with a
.
as noted earlier, setting bash variables does not allow whitespace between the variable name on the LHS, and the variable value on the RHS, of the '=' sign.
awk can do everything and avoid the "awk"ward extra 'grep'. The use of awk's printf is to not add an unnecessary "\n" in the string which would give perl-ish matcher programs conniptions. The variable/parameter expansion for your case in bash doesn't have that issue, so either of these work:
variable=$(ps -ef | awk '/port 10 \-/ {print $12}')
variable=`ps -ef | awk '/port 10 \-/ {print $12}'`
The '-' int the awk record matching pattern removes the need to remove awk itself from the search results.
If you do not have an LDF file then:
1) put the MDF in the C:\Program Files\Microsoft SQL Server\MSSQL13.SQLEXPRESS\MSSQL\DATA\
2) In ssms, go to Databases -> Attach
and add the MDF file. It will not let you add it this way but it will tell you the database name contained within.
3) Make sure the user you are running ssms.exe as has acccess to this MDF file.
4) Now that you know the DbName, run
EXEC sp_attach_single_file_db @dbname = 'DbName',
@physname = N'C:\Program Files\Microsoft SQL Server\MSSQL13.SQLEXPRESS\MSSQL\DATA\yourfile.mdf';
Reference: https://dba.stackexchange.com/questions/12089/attaching-mdf-without-ldf
Looking at :help tabs it doesn't look like vim wants to work the way you do...
Buffers are shared across tabs, so it doesn't seem possible to lock a given buffer to appear only on a certain tab.
It's a good idea, though.
You could probably get the effect you want by using a terminal that supports tabs, like multi-gnome-terminal, then running vim instances in each terminal tab. Not perfect, though...
A workaround is to install http://web.archive.org/web/20060913093359/http://apserver.sourceforge.net:80/ on your local machine, configure it and run gems through this proxy.
PARENT_PROXY
and PARENT_PROXY_PORT
. Enter the values for DOMAIN and USER. Leave PASSWORD blank (nothing after the colon) – you will be prompted when launching it.cd aps097; python main.py
gem install—http-proxy http://localhost:5865/ library
The accepted answer still threw a Javascript error in IE for me (for Angular 1.2 at least). It is a bug but the workaround is to use ngAttr detailed on https://docs.angularjs.org/guide/interpolation
<input type="text" ng-model="inputText" ng-attr-placeholder="{{somePlaceholder}}" />
You need an IP-address-based reverse geocoding API... like the one from ipdata.co. I'm sure there are plenty of options available.
You may want to allow the user to override this, however. For example, they could be on a corporate VPN which makes the IP address look like it's in a different country.
Maybe I missed the point but in reply to NAVY guy here is how the browser can tell you the 'requestor's' IP address (albeit maybe only their service provider).
Place a script tag in the page to be rendered by the client that calls (has src pointing to) another server that is not loaded balanced (I realize that this means you need access to a 2nd server but hosting is cheap these days and you can set this up easily and cheaply).
This is the kind of code that needs to be added to client page:
On the other server "someServerIown" you need to have the ASP, ASPX or PHP page that;
----- contains server code like this:
"<% Response.Write("var clientipaddress = '" & Request.ServerVariables("REMOTE_ADDR") & "';") %>" (without the outside dbl quotes :-))
---- and writes this code back to script tag:
var clientipaddress = '178.32.21.45';
This effectively creates a Javascript variable that you can access with Javascript on the page no less.
Hopefully, you access this var and write the value to a form control ready for sending back.
When the user posts or gets on the next request your Javascript and/or form sends the value of the variable that the "otherServerIown" has filled in for you, back to the server you would like it on.
This is how I get around the dumb load balancer we have that masks the client IP address and makes it appear as that of the Load balancer .... dumb ... dumb dumb dumb!
I haven't given the exact solution because everyone's situation is a little different. The concept is sound, however. Also, note if you are doing this on an HTTPS page your "otherServerIOwn" must also deliver in that secure form otherwise Client is alerted to mixed content. And if you do have https then make sure ALL your certs are valid otherwise client also gets a warning.
Hope it helps someone! Sorry, it took a year to answer/contribute. :-)
If you have a js file that references the jquery, it could be because the js file is in the body and not in the head section (that was my problem). You should move your js file to the head section AFTER the jquery.js reference.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.js"></script>
<script src="myfile.js" type="text/javascript"></script>
</head>
<body>
</body>
</html>
and
, or
:Let's first define a useful function to determine if something is executed or not. A simple function that accepts an argument, prints a message and returns the input, unchanged.
>>> def fun(i):
... print "executed"
... return i
...
One can observe the Python's short-circuiting behavior of and
, or
operators in the following example:
>>> fun(1)
executed
1
>>> 1 or fun(1) # due to short-circuiting "executed" not printed
1
>>> 1 and fun(1) # fun(1) called and "executed" printed
executed
1
>>> 0 and fun(1) # due to short-circuiting "executed" not printed
0
Note: The following values are considered by the interpreter to mean false:
False None 0 "" () [] {}
any()
, all()
:Python's any()
and all()
functions also support short-circuiting. As shown in the docs; they evaluate each element of a sequence in-order, until finding a result that allows an early exit in the evaluation. Consider examples below to understand both.
The function any()
checks if any element is True. It stops executing as soon as a True is encountered and returns True.
>>> any(fun(i) for i in [1, 2, 3, 4]) # bool(1) = True
executed
True
>>> any(fun(i) for i in [0, 2, 3, 4])
executed # bool(0) = False
executed # bool(2) = True
True
>>> any(fun(i) for i in [0, 0, 3, 4])
executed
executed
executed
True
The function all()
checks all elements are True and stops executing as soon as a False is encountered:
>>> all(fun(i) for i in [0, 0, 3, 4])
executed
False
>>> all(fun(i) for i in [1, 0, 3, 4])
executed
executed
False
Additionally, in Python
Comparisons can be chained arbitrarily; for example,
x < y <= z
is equivalent tox < y and y <= z
, except thaty
is evaluated only once (but in both casesz
is not evaluated at all whenx < y
is found to be false).
>>> 5 > 6 > fun(3) # same as: 5 > 6 and 6 > fun(3)
False # 5 > 6 is False so fun() not called and "executed" NOT printed
>>> 5 < 6 > fun(3) # 5 < 6 is True
executed # fun(3) called and "executed" printed
True
>>> 4 <= 6 > fun(7) # 4 <= 6 is True
executed # fun(3) called and "executed" printed
False
>>> 5 < fun(6) < 3 # only prints "executed" once
executed
False
>>> 5 < fun(6) and fun(6) < 3 # prints "executed" twice, because the second part executes it again
executed
executed
False
Edit:
One more interesting point to note :- Logical and
, or
operators in Python returns an operand's value instead of a Boolean (True
or False
). For example:
Operation
x and y
gives the resultif x is false, then x, else y
Unlike in other languages e.g. &&
, ||
operators in C that return either 0 or 1.
Examples:
>>> 3 and 5 # Second operand evaluated and returned
5
>>> 3 and ()
()
>>> () and 5 # Second operand NOT evaluated as first operand () is false
() # so first operand returned
Similarly or
operator return left most value for which bool(value)
== True
else right most false value (according to short-circuiting behavior), examples:
>>> 2 or 5 # left most operand bool(2) == True
2
>>> 0 or 5 # bool(0) == False and bool(5) == True
5
>>> 0 or ()
()
So, how is this useful? One example is given in Practical Python By Magnus Lie Hetland:
Let’s say a user is supposed to enter his or her name, but may opt to enter nothing, in which case you want to use the default value '<Unknown>'
.
You could use an if statement, but you could also state things very succinctly:
In [171]: name = raw_input('Enter Name: ') or '<Unknown>'
Enter Name:
In [172]: name
Out[172]: '<Unknown>'
In other words, if the return value from raw_input
is true (not an empty string), it is assigned to name (nothing changes); otherwise, the default '<Unknown>'
is assigned to name
.
Try:
<xsl:value-of select="count(preceding-sibling::*) + 1" />
Edit - had a brain freeze there, position() is more straightforward!
grep
patterns are matched against individual lines so there is no way for a pattern to match a newline found in the input.
However you can find empty lines like this:
grep '^$' file
grep '^[[:space:]]*$' file # include white spaces
Floating point numbers are represented in scientific notation as a number of only seven significant digits multiplied by a larger number that represents the place of the decimal place. More information about it on Wikipedia:
These Settings worked for me.Cheers!
(WHEN .wsdl is referring to .xsd/schemas using import) If you're using the WMB Tooklit (v8.0.0.4 WMB) then you can find .xsd using following steps :
Create library (optional) > Right Click , New Message Model File > Select SOAP XML > Choose Option 'I already have WSDL for my data' > 'Select file outside workspace' > 'Select the WSDL bindings to Import' (if there are multiple) > Finish.
This will give you the .xsd and .wsdl files in your Workspace (Application Perspective).
a rapid response not tested on several brosers, works on gg chrome / win
-> On focus event -> show/hide password
<input type="password" name="password">
script jQuery
// show on focus
$('input[type="password"]').on('focusin', function(){
$(this).attr('type', 'text');
});
// hide on focus Out
$('input[type="password"]').on('focusout', function(){
$(this).attr('type', 'password');
});
Here's a simple one written in VB for an ASPX page:
If myVar > 1 Then
response.write("Greater than 1")
else
response.write("Not!")
End If
We can three part naming like database_name..object_name
The below query will create the table into our database(with out constraints)
SELECT *
INTO DestinationDB..MyDestinationTable
FROM SourceDB..MySourceTable
Alternatively you could:
INSERT INTO DestinationDB..MyDestinationTable
SELECT * FROM SourceDB..MySourceTable
If your destination table exists and is empty.
Instead of using group concat()
you can use just concat()
Select concat(Col1, ',', Col2) as Foo_Bar from Table1;
edit this only works in mySQL; Oracle concat only accepts two arguments. In oracle you can use something like select col1||','||col2||','||col3 as foobar from table1; in sql server you would use + instead of pipes.
def valid = pointAddress.findAll { a ->
validPointTypes.any { a.contains(it) }
}
Should do it
Just append :after
to your #alertlist li:hover
selector the same way you do with your #alertlist li.selected
selector:
#alertlist li.selected:after, #alertlist li:hover:after
{
position:absolute;
top: 0;
right:-10px;
bottom:0;
border-top: 10px solid transparent;
border-bottom: 10px solid transparent;
border-left: 10px solid #303030;
content: "";
}
You can simply use the indexOf method on the input string:
function hasWhiteSpace(s) {
return s.indexOf(' ') >= 0;
}
Or you can use the test method, on a simple RegEx:
function hasWhiteSpace(s) {
return /\s/g.test(s);
}
This will also check for other white space characters like Tab.
It's little change in boostrap 4. To align navbar to right side, you've to make only two changes. they are:
navbar-nav
class add w-100
as navbar-nav w-100
to make width as 100nav-item dropdown
class add ml-auto
as nav-item dropdown ml-auto
to make margin left as auto.If you didn't understand, please refer the image that i've attached to this.
Full source code
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand" href="#">Navbar</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNavDropdown">
<ul class="navbar-nav w-100">
<li class="nav-item active">
<a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Features</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Pricing</a>
</li>
<li class="nav-item dropdown ml-auto">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Dropdown link
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
<a class="dropdown-item" href="#">Action</a>
<a class="dropdown-item" href="#">Another action</a>
<a class="dropdown-item" href="#">Something else here</a>
</div>
</li>
</ul>
</div>
</nav>
Note: if you're just looking for the names of changed files (without the line numbers for lines that were changed), that's easy, click this link to another answer here.
There's no built-in option for this (and I don't think it's all that useful either), but it is possible to do this in git, with the help of an "external diff" script.
Here's a pretty crappy one; it will be up to you to fix up the output the way you would like it.
#! /bin/sh
#
# run this with:
# GIT_EXTERNAL_DIFF=<name of script> git diff ...
#
case $# in
1) "unmerged file $@, can't show you line numbers"; exit 1;;
7) ;;
*) echo "I don't know what to do, help!"; exit 1;;
esac
path=$1
old_file=$2
old_hex=$3
old_mode=$4
new_file=$5
new_hex=$6
new_mode=$7
printf '%s: ' $path
diff $old_file $new_file | grep -v '^[<>-]'
For details on "external diff" see the description of GIT_EXTERNAL_DIFF
in the git manual page (around line 700, pretty close to the end).
You're trying to assign three separate string literals to a single string variable. A valid string variable would be 'John, Sarah, George'
. If you want embedded single quotes between the double quotes, you have to escape them.
Also, your actual SELECT
won't work, because SQL databases won't parse the string variable out into individual literal values. You need to use dynamic SQL instead, and then execute that dynamic SQL statement. (Search this site for dynamic SQL
, with the database engine you're using as the topic (as in [sqlserver] dynamic SQL
), and you should get several examples.)
I known this is old, but I found a easier solution and it works on ie10, firefox and chrome:
<div id="wrapper">
<div id="one">One</div>
<div id="two">Two</div>
<div id="three">Three</div>
</div>
This is the css:
#wrapper {display:table;}
#one {display:table-footer-group;}
#three {display:table-header-group;}
And the result:
"Three"
"Two"
"One"
I found it here.
I was with the same problem except with a slight difference, the version of PHPMailer 6.0, by the good friend avs099 I know that the new version of PHPMailer since February 2018 does not support the autoload, and had a serious problem to instantiate the libraries with the namespace in MVC, I leave the code for those who need it.
//Controller
protected function getLibraryWNS($libreria) {
$rutaLibreria = ROOT . 'libs' . DS . $libreria . '.php';
if(is_readable($rutaLibreria)){
require_once $rutaLibreria;
echo $rutaLibreria . '<br/>';
}
else{
throw new Exception('Error de libreria');
}
}
//loginController
public function enviarEmail($email, $nombre, $asunto, $cuerpo){
//Import the PHPMailer class into the global namespace
$this->getLibraryWNS('PHPMailer');
$this->getLibraryWNS('SMTP');
//Create a new PHPMailer instance
$mail = new \PHPMailer\PHPMailer\PHPMailer();
//Tell PHPMailer to use SMTP
$mail->isSMTP();
//Enable SMTP debugging
// $mail->SMTPDebug = 0; // 0 = off (for production use), 1 = client messages, 2 = client and server messages Godaddy POR CONFIRMAR
$mail->SMTPDebug = 1; // debugging: 1 = errors and messages, 2 = messages only
//Whether to use SMTP authentication
$mail->SMTPAuth = true; // authentication enabled
//Set the encryption system to use - ssl (deprecated) or tls
$mail->SMTPSecure = 'ssl'; //Seguridad Correo Gmail
//Set the hostname of the mail server
$mail->Host = "smtp.gmail.com"; //Host Correo Gmail
//Set the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission
$mail->Port = 465; //587;
//Verifica si el servidor acepta envios en HTML
$mail->IsHTML(true);
//Username to use for SMTP authentication - use full email address for gmail
$mail->Username = '[email protected]';
//Password to use for SMTP authentication
$mail->Password = 'tucontraseña';
//Set who the message is to be sent from
$mail->setFrom('[email protected]','Creador de Páginas Web');
$mail->Subject = $asunto;
$mail->Body = $cuerpo;
//Set who the message is to be sent to
$mail->addAddress($email, $nombre);
//Send the message, check for errors
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
return false;
} else {
echo "Message has been sent";
return true;
}
Which version of .NET are you using? If it's .NET 3.5, I'd just call ToArray()
and be done with it.
If you only have a non-generic IEnumerable, do something like this:
IEnumerable query = ...;
MyEntityType[] array = query.Cast<MyEntityType>().ToArray();
If you don't know the type within that method but the method's callers do know it, make the method generic and try this:
public static void T[] PerformQuery<T>()
{
IEnumerable query = ...;
T[] array = query.Cast<T>().ToArray();
return array;
}
To check if a string variable contains a valid email address, the easiest way is to test it against a regular expression. There is a good discussion of various regex's and their trade-offs at regular-expressions.info.
Here is a relatively simple one that leans on the side of allowing some invalid addresses through: ^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,6}$
How you can use regular expressions depends on the version of iOS you are using.
You can use NSRegularExpression
, which allows you to compile and test against a regular expression directly.
Does not include the NSRegularExpression
class, but does include NSPredicate
, which can match against regular expressions.
NSString *emailRegex = ...;
NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
BOOL isValid = [emailTest evaluateWithObject:checkString];
Read a full article about this approach at cocoawithlove.com.
Does not include any regular expression matching in the Cocoa libraries. However, you can easily include RegexKit Lite in your project, which gives you access to the C-level regex APIs included on iOS 2.0.
Since Spring 4.0+, the best solution is to annotate the test method with @WithMockUser
@Test
@WithMockUser(username = "user1", password = "pwd", roles = "USER")
public void mytest1() throws Exception {
mockMvc.perform(get("/someApi"))
.andExpect(status().isOk());
}
Remember to add the following dependency to your project
'org.springframework.security:spring-security-test:4.2.3.RELEASE'
In my case I use a web hosting but it´s the same in local host, I used:
ps -aef | grep 'node'
for watch the node process then, the console shows the process with PID. for kill the process you have to use this command:
kill -9 PID
where PID is the process id from the command above.
You can use max() to get the max value. The max function can also return the index of the maximum value in the vector. To get this, assign the result of the call to max to a two element vector instead of just a single variable.
e.g. z is your array,
>> [x, y] = max(z)
x =
7
y =
4
Here, 7 is the largest number at the 4th position(index).
In Swift 4 and 5. I created a closure variable containing two parameter dictionary and bool.
var completionHandler:([String:Any], Bool)->Void = { dict, success in
if success {
print(dict)
}
}
Calling the closure variable
self.completionHandler(["name":"Gurjinder singh"],true)
Another solution is:
SELECT * FROM TABLE1 WHERE id NOT IN (SELECT id FROM TABLE2)
As soon as a WHEN statement is true the break is implicit.
You will have to concider which WHEN Expression is the most likely to happen. If you put that WHEN at the end of a long list of WHEN statements, your sql is likely to be slower. So put it up front as the first.
More information here: break in case statement in T-SQL
Although you cannot use import
without running the code; there is quite a swift way in which you can input your variables; by using numpy.savez
, which stores variables as numpy arrays in a .npz file. Afterwards you can load the variables using numpy.load
.
See a full description in the scipy documentation
Please note this is only the case for variables and arrays of variable, and not for methods, etc.
Try this:
$Date = $row['valdate']->format('d/m/Y'); // the result will 01/12/2015
NOTE: $row['valdate']
its a value date in the database
You're passing link=$a
and link=$b
in the hrefs for A and B, respectively. They are treated as strings, not variables. The following should fix that for you:
echo '<a href="pass.php?link=' . $a . '">Link 1</a>';
// and
echo '<a href="pass.php?link=' . $b . '">Link 2</a>';
The value of $a
also isn't included on pass.php
. I would suggest making a common variable file and include it on all necessary pages.
If you only need to prevent line-breaks on space characters, you can use
entities between words:
No line break
instead of
<span style="white-space:nowrap">No line break</span>
Symfony 3.0
Prior to Symfony 2.6
you would use SecurityContext
.
SecurityContext
will be deprecated in Symfony 3.0
in favour of the AuthorizationChecker
.
For Symfony 2.6+
& Symfony 3.0
use AuthorizationChecker
.
// Get our Security Context Object - [deprecated in 3.0]
$security_context = $this->get('security.context');
# e.g: $security_context->isGranted('ROLE_ADMIN');
// Get our Token (representing the currently logged in user)
$security_token = $security_context->getToken();
# e.g: $security_token->getUser();
# e.g: $security_token->isAuthenticated();
# [Careful] ^ "Anonymous users are technically authenticated"
// Get our user from that security_token
$user = $security_token->getUser();
# e.g: $user->getEmail(); $user->isSuperAdmin(); $user->hasRole();
// Check for Roles on the $security_context
$isRoleAdmin = $security_context->isGranted('ROLE_ADMIN');
# e.g: (bool) true/false
security.context
becomes security.authorization_checker
.
We now get our token from security.token_storage
instead of the security.context
// [New 3.0] Get our "authorization_checker" Object
$auth_checker = $this->get('security.authorization_checker');
# e.g: $auth_checker->isGranted('ROLE_ADMIN');
// Get our Token (representing the currently logged in user)
// [New 3.0] Get the `token_storage` object (instead of calling upon `security.context`)
$token = $this->get('security.token_storage')->getToken();
# e.g: $token->getUser();
# e.g: $token->isAuthenticated();
# [Careful] ^ "Anonymous users are technically authenticated"
// Get our user from that token
$user = $token->getUser();
# e.g (w/ FOSUserBundle): $user->getEmail(); $user->isSuperAdmin(); $user->hasRole();
// [New 3.0] Check for Roles on the $auth_checker
$isRoleAdmin = $auth_checker->isGranted('ROLE_ADMIN');
// e.g: (bool) true/false
Read more here in the docs: AuthorizationChecker
How to do this in twig?: Symfony 2: How do I check if a user is not logged in inside a template?
Try setting the "endOfLine":"auto"
in your .prettierrc file (inside the object)
Or set
"prettier/prettier": ["error", {
..
"endOfLine":"auto"
..
}],
inside the rules object of the eslintrc file.
If you are using windows machine endOfLine can be "crlf" basing on your git config.
You've got the right idea, so here's how to go ahead: the onclick
handlers run on the client side, in the browser, so you cannot call a PHP function directly. Instead, you need to add a JavaScript function that (as you mentioned) uses AJAX to call a PHP script and retrieve the data. Using jQuery, you can do something like this:
<script type="text/javascript">
function recp(id) {
$('#myStyle').load('data.php?id=' + id);
}
</script>
<a href="#" onClick="recp('1')" > One </a>
<a href="#" onClick="recp('2')" > Two </a>
<a href="#" onClick="recp('3')" > Three </a>
<div id='myStyle'>
</div>
Then you put your PHP code into a separate file: (I've called it data.php
in the above example)
<?php
require ('myConnect.php');
$id = $_GET['id'];
$results = mysql_query("SELECT para FROM content WHERE para_ID='$id'");
if( mysql_num_rows($results) > 0 )
{
$row = mysql_fetch_array( $results );
echo $row['para'];
}
?>
Use
../
For example if your file, lets say image is in folder1
in folder2
you locate it this way
../folder1/folder2/image
You're not actually passing the model to the Partial, you're passing a new ViewDataDictionary<LetLord.Models.Tenant>()
. Try this:
@model LetLord.Models.Tenant
<div class="row-fluid">
<div class="span4 well-border">
@Html.Partial("~/Views/Tenants/_TenantDetailsPartial.cshtml", Model)
</div>
</div>
Use this code for read file with all type of extension file.
string[] sDirectoryInfo = Directory.GetFiles(SourcePath, "*.*");
Add the following code in viewDidLoad or loadView
self.navigationController.navigationBar.topItem.title = @"";
I tested it in iPhone and iPad with iOS 9
Sudo is a Unix specific command designed to allow a user to carry out administrative tasks with the appropriate permissions.
Windows does not have (need?) this.
Run the command with the sudo removed from the start.
If you have a single-threaded application, you can use a simple try/catch in the Main function, however, this does not cover exceptions that may be thrown outside of the Main function, on other threads, for example (as noted in other comments). This code demonstrates how an exception can cause the application to terminate even though you tried to handle it in Main (notice how the program exits gracefully if you press enter and allow the application to exit gracefully before the exception occurs, but if you let it run, it terminates quite unhappily):
static bool exiting = false;
static void Main(string[] args)
{
try
{
System.Threading.Thread demo = new System.Threading.Thread(DemoThread);
demo.Start();
Console.ReadLine();
exiting = true;
}
catch (Exception ex)
{
Console.WriteLine("Caught an exception");
}
}
static void DemoThread()
{
for(int i = 5; i >= 0; i--)
{
Console.Write("24/{0} =", i);
Console.Out.Flush();
Console.WriteLine("{0}", 24 / i);
System.Threading.Thread.Sleep(1000);
if (exiting) return;
}
}
You can receive notification of when another thread throws an exception to perform some clean up before the application exits, but as far as I can tell, you cannot, from a console application, force the application to continue running if you do not handle the exception on the thread from which it is thrown without using some obscure compatibility options to make the application behave like it would have with .NET 1.x. This code demonstrates how the main thread can be notified of exceptions coming from other threads, but will still terminate unhappily:
static bool exiting = false;
static void Main(string[] args)
{
try
{
System.Threading.Thread demo = new System.Threading.Thread(DemoThread);
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
demo.Start();
Console.ReadLine();
exiting = true;
}
catch (Exception ex)
{
Console.WriteLine("Caught an exception");
}
}
static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
Console.WriteLine("Notified of a thread exception... application is terminating.");
}
static void DemoThread()
{
for(int i = 5; i >= 0; i--)
{
Console.Write("24/{0} =", i);
Console.Out.Flush();
Console.WriteLine("{0}", 24 / i);
System.Threading.Thread.Sleep(1000);
if (exiting) return;
}
}
So in my opinion, the cleanest way to handle it in a console application is to ensure that every thread has an exception handler at the root level:
static bool exiting = false;
static void Main(string[] args)
{
try
{
System.Threading.Thread demo = new System.Threading.Thread(DemoThread);
demo.Start();
Console.ReadLine();
exiting = true;
}
catch (Exception ex)
{
Console.WriteLine("Caught an exception");
}
}
static void DemoThread()
{
try
{
for (int i = 5; i >= 0; i--)
{
Console.Write("24/{0} =", i);
Console.Out.Flush();
Console.WriteLine("{0}", 24 / i);
System.Threading.Thread.Sleep(1000);
if (exiting) return;
}
}
catch (Exception ex)
{
Console.WriteLine("Caught an exception on the other thread");
}
}
My below code solve this issue, but i suggest First of all you need to understand what causing this issue and try the solution which you can find by changing code
I can give another way to solve this issue but better solution is to check your coding structure and try to analyse what makes this happen,if you do not find any solution then you can go with this code below
try{
Start:
///Put your file access code here
}catch (Exception ex)
{
//by anyway you need to handle this error with below code
if (ex.Message.StartsWith("The process cannot access the file"))
{
//Wait for 5 seconds to free that file and then start execution again
Thread.Sleep(5000);
goto Start;
}
}
You can use JSONPath
Doing something like this:
results = JSONPath(null, TestObj, "$..[?(@.id=='A')]")
Note that JSONPath returns an array of results
(I have not tested the expression "$..[?(@.id=='A')]" btw. Maybe it needs to be fine-tuned with the help of a browser console)
Here's a simple solution. I'm using Python 2.7 and Windows 7.
What you're trying to install requires a C/C++ compiler but Python isn't finding it. A lot of Python packages are actually written in C/C++ and need to be compiled. vcvarsall.bat is needed to compile C++ and pip is assuming your machine can do that.
Try upgrading setuptools first, because v6.0 and above will automatically detect a compiler. You might already have a compiler but Python can't find it. Open up a command line and type:
pip install --upgrade setuptools
Now try and install your package again:
pip install [yourpackagename]
If that didn't work, then it's certain you don't have a compiler, so you'll need to install one:
http://www.microsoft.com/en-us/download/details.aspx?id=44266
Now try again:
pip install [yourpackagename]
And there you go. It should work for you.
position: static
, which means the element is not positioned and occurs where it normally would in the document. Normally you wouldn't specify this unless you needed to override a positioning that had been previously set.position: relative
, then you can use top or bottom, and left or right to move the element relative to where it would normally occur in the document.position: absolute
, the element is removed from the document and placed exactly where you tell it to go.So in regard to your question you should position the containing block relative, i.e:
#parent {
position: relative;
}
And the child element you should position absolute to the parent element like this:
#child {
position: absolute;
}
Another thing to note that if you have a symbolic link from a non public location which hosts your project code to say public_html - running php artisan
in the symbolic link location (public_html) will result in this error.
You seem to need to be in the actual project directory for php artisan
to work.
The JSON spec requires UTF-8 support by decoders. As a result, all JSON decoders can handle UTF-8 just as well as they can handle the numeric escape sequences. This is also the case for Javascript interpreters, which means JSONP will handle the UTF-8 encoded JSON as well.
The ability for JSON encoders to use the numeric escape sequences instead just offers you more choice. One reason you may choose the numeric escape sequences would be if a transport mechanism in between your encoder and the intended decoder is not binary-safe.
Another reason you may want to use numeric escape sequences is to prevent certain characters appearing in the stream, such as <
, &
and "
, which may be interpreted as HTML sequences if the JSON code is placed without escaping into HTML or a browser wrongly interprets it as HTML. This can be a defence against HTML injection or cross-site scripting (note: some characters MUST be escaped in JSON, including "
and \
).
Some frameworks, including PHP's implementation of JSON, always do the numeric escape sequences on the encoder side for any character outside of ASCII. This is intended for maximum compatibility with limited transport mechanisms and the like. However, this should not be interpreted as an indication that JSON decoders have a problem with UTF-8.
So, I guess you just could decide which to use like this:
Just use UTF-8, unless your method of storage or transport between encoder and decoder is not binary-safe.
Otherwise, use the numeric escape sequences.
To bind socket with localhost, before you invoke the bind function, sin_addr.s_addr field of the sockaddr_in structure should be set properly. The proper value can be obtained either by
my_sockaddress.sin_addr.s_addr = inet_addr("127.0.0.1")
or by
my_sockaddress.sin_addr.s_addr=htonl(INADDR_LOOPBACK);
I did it this way:
var xlApp = new Excel.Application();
var xlWorkBook = xlApp.Workbooks.Add(System.Reflection.Missing.Value);
var xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.Item[1];
xlWorkSheet.Columns.AutoFit();
With this way, columns always fit to text width inside cells.
Hope it helps to someone!
There's an algorithm on wikipedia to determine leap years:
function isLeapYear (year):
if ((year modulo 4 is 0) and (year modulo 100 is not 0))
or (year modulo 400 is 0)
then true
else false
There's a lot of information about this topic on the wikipedia page about leap years, inclusive information about different calendars.
You can create a way to define static constants on a class using an odd feature of ES6 classes. Since statics are inherited by their subclasses, you can do the following:
const withConsts = (map, BaseClass = Object) => {
class ConstClass extends BaseClass { }
Object.keys(map).forEach(key => {
Object.defineProperty(ConstClass, key, {
value: map[key],
writable : false,
enumerable : true,
configurable : false
});
});
return ConstClass;
};
class MyClass extends withConsts({ MY_CONST: 'this is defined' }) {
foo() {
console.log(MyClass.MY_CONST);
}
}
Use shortcut Alt+Shift+W or navigate to Windows->Show View->Project Explorer
If your integer is timestamp in milliseconds use:
SELECT strftime("%Y-%d-%m", col_name, 'unixepoch') AS col_name
It will format milliseconds to yyyy-mm-dd string.
If you need to remove a lot of keys from a dictionary in one line of code, I think using map() is quite succinct and Pythonic readable:
myDict = {'a':1,'b':2,'c':3,'d':4}
map(myDict.pop, ['a','c']) # The list of keys to remove
>>> myDict
{'b': 2, 'd': 4}
And if you need to catch errors where you pop a value that isn't in the dictionary, use lambda inside map() like this:
map(lambda x: myDict.pop(x,None), ['a', 'c', 'e'])
[1, 3, None] # pop returns
>>> myDict
{'b': 2, 'd': 4}
or in python3
, you must use a list comprehension instead:
[myDict.pop(x, None) for x in ['a', 'c', 'e']]
It works. And 'e' did not cause an error, even though myDict did not have an 'e' key.
Java doesn't want you to make an array of HashMaps, but it will let you make an array of Objects. So, just write up a class declaration as a shell around your HashMap, and make an array of that class. This lets you store some extra data about the HashMaps if you so choose--which can be a benefit, given that you already have a somewhat complex data structure.
What this looks like:
private static someClass[] arr = new someClass[someNum];
and
public class someClass {
private static int dataFoo;
private static int dataBar;
private static HashMap<String, String> yourArray;
...
}
In my opinion this is the simplest solution
$orderby = 'name';
$order = 'asc';
$hide_empty = false ;
$cat_args = array(
'orderby' => $orderby,
'order' => $order,
'hide_empty' => $hide_empty,
);
$product_categories = get_terms( 'product_cat', $cat_args );
if( !empty($product_categories) ){
echo '
<ul>';
foreach ($product_categories as $key => $category) {
echo '
<li>';
echo '<a href="'.get_term_link($category).'" >';
echo $category->name;
echo '</a>';
echo '</li>';
}
echo '</ul>
';
}
You can use sys.master_files.
Contains a row per file of a database as stored in the master database. This is a single, system-wide view.
if You are using browser it default always works on get, u can work with postman tool,otherwise u can change it to getmapping.hope this will works
If (as I understand) you're trying to completely block inheritance in the web config of your child application, I suggest you to avoid using the tag in web.config.
Instead create a new apppool and edit the applicationHost.config file (located in %WINDIR%\System32\inetsrv\Config and %WINDIR%\SysWOW64\inetsrv\config).
You just have to find the entry for your apppool and add the attribute enableConfigurationOverride="false"
like in the following example:
<add name="MyAppPool" autoStart="true" managedRuntimeVersion="v4.0" managedPipelineMode="Integrated" enableConfigurationOverride="false">
<processModel identityType="NetworkService" />
</add>
This will avoid configuration inheritance in the applications served by MyAppPool.
Matteo
When we write VBA code it is often desired to have the VBA Macro code not visible to end-users. This is to protect your intellectual property and/or stop users messing about with your code. Just be aware that Excel's protection ability is far from what would be considered secure. There are also many VBA Password Recovery [tools] for sale on the www.
To protect your code, open the Excel Workbook and go to Tools>Macro>Visual Basic Editor (Alt+F11). Now, from within the VBE go to Tools>VBAProject Properties and then click the Protection page tab and then check "Lock project from viewing" and then enter your password and again to confirm it. After doing this you must save, close & reopen the Workbook for the protection to take effect.
(Emphasis mine)
Seems like your best bet. It won't stop people determined to steal your code but it's enough to stop casual pirates.
Remember, even if you were able to distribute a compiled copy of your code there'd be nothing to stop people decompiling it.
You can use jQuery to achieve this using simple $.get
method. .html
work like innerHtml and replace the content of your div.
$.get("/YourUrl", {},
function (returnedHtml) {
$("#here").html(returnedHtml);
});
And call this using javascript setInterval
method.
see event.data
commentbtn.bind('click', { id: '12', name: 'Chuck Norris' }, function(event) {
var data = event.data;
alert(data.id);
alert(data.name);
});
If your data is initialized before binding the event, then simply capture those variables in a closure.
// assuming id and name are defined in this scope
commentBtn.click(function() {
alert(id), alert(name);
});
First and foremost, I highly recommend you buy the PDF/E-Book from PHP Architect. It's US$20, but is the only straightforward "Here's how Magento works" resource I've been able to find. I've also started writing Magento tutorials at my own website.
Second, if you have a choice, and aren't an experienced programmer or don't have access to an experienced programmer (ideally in PHP and Java), pick another cart. Magento is well engineered, but it was engineered to be a shopping cart solution that other programmers can build modules on top of. It was not engineered to be easily understood by people who are smart, but aren't programmers.
Third, Magento MVC is very different from the Ruby on Rails, Django, CodeIgniter, CakePHP, etc. MVC model that's popular with PHP developers these days. I think it's based on the Zend model, and the whole thing is very Java OOP-like. There's two controllers you need to be concerned about. The module/frontName controller, and then the MVC controller.
Fourth, the Magento application itself is built using the same module system you'll be using, so poking around the core code is a useful learning tactic. Also, a lot of what you'll be doing with Magento is overriding existing classes. What I'm covering here is creating new functionality, not overriding. Keep this in mind when you're looking at the code samples out there.
I'm going to start with your first question, showing you how to setup a controller/router to respond to a specific URL. This will be a small novel. I might have time later for the model/template related topics, but for now, I don't. I will, however, briefly speak to your SQL question.
Magento uses an EAV database architecture. Whenever possible, try to use the model objects the system provides to get the information you need. I know it's all there in the SQL tables, but it's best not to think of grabbing data using raw SQL queries, or you'll go mad.
Final disclaimer. I've been using Magento for about two or three weeks, so caveat emptor. This is an exercise to get this straight in my head as much as it is to help Stack Overflow.
All additions and customizations to Magento are done through modules. So, the first thing you'll need to do is create a new module. Create an XML file in app/modules
named as follows
cd /path/to/store/app
touch etc/modules/MyCompanyName_HelloWorld.xml
<?xml version="1.0"?>
<config>
<modules>
<MyCompanyName_HelloWorld>
<active>true</active>
<codePool>local</codePool>
</MyCompanyName_HelloWorld>
</modules>
</config>
MyCompanyName is a unique namespace for your modifications, it doesn't have to be your company's name, but that the recommended convention my magento. HelloWorld
is the name of your module.
Now that the module file is in place, we'll need to let Magento know about it (and check our work). In the admin application
Now, we make sure that Magento knows about the module
If you can live with the performance slow down, you might want to turn off the application cache while developing/learning. Nothing is more frustrating then forgetting the clear out the cache and wondering why your changes aren't showing up.
Next, we'll need to setup a directory structure for the module. You won't need all these directories, but there's no harm in setting them all up now.
mkdir -p app/code/local/MyCompanyName/HelloWorld/Block
mkdir -p app/code/local/MyCompanyName/HelloWorld/controllers
mkdir -p app/code/local/MyCompanyName/HelloWorld/Model
mkdir -p app/code/local/MyCompanyName/HelloWorld/Helper
mkdir -p app/code/local/MyCompanyName/HelloWorld/etc
mkdir -p app/code/local/MyCompanyName/HelloWorld/sql
And add a configuration file
touch app/code/local/MyCompanyName/HelloWorld/etc/config.xml
and inside the configuration file, add the following, which is essentially a "blank" configuration.
<?xml version="1.0"?>
<config>
<modules>
<MyCompanyName_HelloWorld>
<version>0.1.0</version>
</MyCompanyName_HelloWorld>
</modules>
</config>
Oversimplifying things, this configuration file will let you tell Magento what code you want to run.
Next, we need to setup the module's routers. This will let the system know that we're handling any URLs in the form of
http://example.com/magento/index.php/helloworld
So, in your configuration file, add the following section.
<config>
<!-- ... -->
<frontend>
<routers>
<!-- the <helloworld> tagname appears to be arbitrary, but by
convention is should match the frontName tag below-->
<helloworld>
<use>standard</use>
<args>
<module>MyCompanyName_HelloWorld</module>
<frontName>helloworld</frontName>
</args>
</helloworld>
</routers>
</frontend>
<!-- ... -->
</config>
What you're saying here is "any URL with the frontName of helloworld ...
http://example.com/magento/index.php/helloworld
should use the frontName controller MyCompanyName_HelloWorld".
So, with the above configuration in place, when you load the helloworld page above, you'll get a 404 page. That's because we haven't created a file for our controller. Let's do that now.
touch app/code/local/MyCompanyName/HelloWorld/controllers/IndexController.php
Now try loading the page. Progress! Instead of a 404, you'll get a PHP/Magento exception
Controller file was loaded but class does not exist
So, open the file we just created, and paste in the following code. The name of the class needs to be based on the name you provided in your router.
<?php
class MyCompanyName_HelloWorld_IndexController extends Mage_Core_Controller_Front_Action{
public function indexAction(){
echo "We're echoing just to show that this is what's called, normally you'd have some kind of redirect going on here";
}
}
What we've just setup is the module/frontName controller.
This is the default controller and the default action of the module.
If you want to add controllers or actions, you have to remember that the tree first part of a Magento URL are immutable they will always go this way http://example.com/magento/index.php/frontName/controllerName/actionName
So if you want to match this url
http://example.com/magento/index.php/helloworld/foo
You will have to have a FooController, which you can do this way :
touch app/code/local/MyCompanyName/HelloWorld/controllers/FooController.php
<?php
class MyCompanyName_HelloWorld_FooController extends Mage_Core_Controller_Front_Action{
public function indexAction(){
echo 'Foo Index Action';
}
public function addAction(){
echo 'Foo add Action';
}
public function deleteAction(){
echo 'Foo delete Action';
}
}
Please note that the default controller IndexController and the default action indexAction can by implicit but have to be explicit if something come after it.
So http://example.com/magento/index.php/helloworld/foo
will match the controller FooController and the action indexAction and NOT the action fooAction of the IndexController. If you want to have a fooAction, in the controller IndexController you then have to call this controller explicitly like this way :
http://example.com/magento/index.php/helloworld/index/foo
because the second part of the url is and will always be the controllerName.
This behaviour is an inheritance of the Zend Framework bundled in Magento.
You should now be able to hit the following URLs and see the results of your echo statements
http://example.com/magento/index.php/helloworld/foo
http://example.com/magento/index.php/helloworld/foo/add
http://example.com/magento/index.php/helloworld/foo/delete
So, that should give you a basic idea on how Magento dispatches to a controller. From here I'd recommended poking at the existing Magento controller classes to see how models and the template/layout system should be used.
Make file executable:
chmod +x file
Find location of perl:
which perl
This should return something like
/bin/perl sometimes /usr/local/bin
Then in the first line of your script add:
#!"path"/perl with path from above e.g.
#!/bin/perl
Then you can execute the file
./file
There may be some issues with the PATH, so you may want to change that as well ...
I solved this problem in accordance with the figure:
run in cmd
npm install -g @angular/cli
and then
( open in Windows 10) Control Panel\All Control Panel Items\System or accordance with the figure
step 1:
step 2 :
step3:
step4:
step5: add missing ng path
Finally, restart all opened command prompts, or you can also restart the computer.
This is MUCH more than the OP asked for, but since this is a top result for securely passing passwords to curl
, I'm adding these solutions here for others who arrive here searching for that.
NOTE: -s
arg for read
command is not POSIX, and so is not available everywhere, so it won't be used below. We will use stty -echo
and stty echo
instead.
NOTE: All bash variables below could instead be declared as locals if in a function, rather than unsetting.
NOTE: perl
is pretty generally available on all systems I've tried due to it being a dependency for many things, whereas ruby
and python
are not, so using perl
here. If you can guarantee ruby
/python
where you're doing this, you can replace the perl
command with their equivalent.
NOTE: Tested in bash
3.2.57 on macOS 10.14.4. Some small translation may be required for other shells/installs.
Securely prompt a user for a (reusable) password to pass to curl. Particularly useful if you need to call curl multiple times.
For modern shells, where echo
is a built-in (check via which echo
):
url='https://example.com'
printf "Username: "
read username
printf "Password: "
stty -echo # disables echoing user input, POSIX equivalent for 'read -s'
read pass
printf "\n" # we need to move the line ahead
stty echo # re-enable echoing user input
echo ${pass} | sed -e "s/^/-u ${username}:/" | curl --url "${url}" -K-
unset username
unset pass
For older shells, where echo
is something like /bin/echo
(where whatever it echos can be seen in the process list):
THIS VERSION CANNOT REUSE THE PASSWORD, see lower down instead.
url='https://example.com'
printf "Username: "
read username
printf "Password: "
stty -echo # disables echoing user input, POSIX equivalent for 'read -s'
perl -e '
my $val=<STDIN>;
chomp $val;
print STDERR "\n"; # we need to move the line ahead, but not send a newline down the pipe
print $val;
' | sed -e "s/^/-u ${username}:/" | curl --url "${url}" -K-
stty echo # re-enable echoing user input
unset username
If you happen to need to store the password temporarily to a file, to re-use it for multiple commands before clearing it (say because you're using functions for code re-use and don't want to repeat code and can't pass the value around via echo). (Yes, these are a little contrived looking in this form not being functions in different libraries; I tried to reduce them to the minimum code needed to show it.)
When echo is built-in (this is especially contrived, since echo is a built-in, but provided for completeness):
url='https://example.com'
filepath="$(mktemp)" # random path, only readable by current user
printf "Username: "
read username
printf "Password: "
stty -echo # disables echoing user input, POSIX equivalent for 'read -s'
read pass
echo "${pass}" > "${filepath}"
unset pass
printf "\n" # we need to move the line ahead
stty echo # re-enable echoing user input
cat "${filepath}" | sed -e "s/^/-u ${username}:/" | curl --url "${url}" -K-
rm "${filepath}" # don't forget to delete the file when done!!
unset username
When echo is something like /bin/echo
:
url='https://example.com'
filepath="$(mktemp)" # random path, only readable by current user
printf "Username: "
read username
printf "Password: "
stty -echo # disables echoing user input, POSIX equivalent for 'read -s'
$(perl -e '
my $val=<STDIN>;
chomp $val;
open(my $fh, ">", $ARGV[0]) or die "Could not open file \"$ARGV[0]\" $\!";
print $fh $val;
close $fh;
' "$filepath")
printf "\n" # we need to move the line ahead
stty echo # re-enable echoing user input
cat "${filepath}" | sed -e "s/^/-u ${username}:/" | curl --url "${url}" -K-
rm "${filepath}" # don't forget to delete the file when done!!
unset username
the above solutions wont work on ipad-2
recently I had an safari browser crash issue while plotting the markers even if there are less number of markers. Initially I was using marker with label (markerwithlabel.js) library for plotting the marker , when i use google native marker it was working fine even with large number of markers but i want customized markers , so i refer the above solution given by jonathan but still the crashing issue is not resolved after doing lot of research i came to know about http://nickjohnson.com/b/google-maps-v3-how-to-quickly-add-many-markers this blog and now my map search is working smoothly on ipad-2 :)
Quick and easy for inline, use bellow code:
new Random().Next(min, max);
// for example unique name
strName += "_" + new Random().Next(100, 999);
The .NET Data Providers consist of a number of classes used to connect to a data source, execute commands, and return recordsets. The Command Object in ADO.NET provides a number of Execute methods that can be used to perform the SQL queries in a variety of fashions.
A stored procedure is a pre-compiled executable object that contains one or more SQL statements. In many cases stored procedures accept input parameters and return multiple values . Parameter values can be supplied if a stored procedure is written to accept them. A sample stored procedure with accepting input parameter is given below :
CREATE PROCEDURE SPCOUNTRY
@COUNTRY VARCHAR(20)
AS
SELECT PUB_NAME FROM publishers WHERE COUNTRY = @COUNTRY
GO
The above stored procedure is accepting a country name (@COUNTRY VARCHAR(20)) as parameter and return all the publishers from the input country. Once the CommandType is set to StoredProcedure, you can use the Parameters collection to define parameters.
command.CommandType = CommandType.StoredProcedure;
param = new SqlParameter("@COUNTRY", "Germany");
param.Direction = ParameterDirection.Input;
param.DbType = DbType.String;
command.Parameters.Add(param);
The above code passing country parameter to the stored procedure from C# application.
using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string connetionString = null;
SqlConnection connection ;
SqlDataAdapter adapter ;
SqlCommand command = new SqlCommand();
SqlParameter param ;
DataSet ds = new DataSet();
int i = 0;
connetionString = "Data Source=servername;Initial Catalog=PUBS;User ID=sa;Password=yourpassword";
connection = new SqlConnection(connetionString);
connection.Open();
command.Connection = connection;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "SPCOUNTRY";
param = new SqlParameter("@COUNTRY", "Germany");
param.Direction = ParameterDirection.Input;
param.DbType = DbType.String;
command.Parameters.Add(param);
adapter = new SqlDataAdapter(command);
adapter.Fill(ds);
for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
MessageBox.Show (ds.Tables[0].Rows[i][0].ToString ());
}
connection.Close();
}
}
}
The very simplest way would be to run Eclipse CDT on the Linux Box and use either X11-Forwarding or remote desktop software such as VNC.
This, of course, is only possible when you Eclipse is present on the Linux box and your network connection to the box is sufficiently fast.
The advantage is that, due to everything being local, you won't have synchronization issues, and you don't get any awkward cross-platform issues.
If you have no eclipse on the box, you could thinking of sharing your linux working directory via SMB (or SSHFS) and access it from your windows machine, but that would require quite some setup.
Both would be better than having two copies, especially when it's cross-platform.
Wikipedia has a very good answer http://en.wikipedia.org/wiki/Universally_unique_identifier#Collisions
the number of random version 4 UUIDs which need to be generated in order to have a 50% probability of at least one collision is 2.71 quintillion, computed as follows:
...
This number is equivalent to generating 1 billion UUIDs per second for about 85 years, and a file containing this many UUIDs, at 16 bytes per UUID, would be about 45 exabytes, many times larger than the largest databases currently in existence, which are on the order of hundreds of petabytes.
...
Thus, for there to be a one in a billion chance of duplication, 103 trillion version 4 UUIDs must be generated.
You can simply use matches
method of String class.
boolean result = someString.matches("stores.*store.*product.*");
If you are using Python 3, you can use concurrent.futures.ProcessPoolExecutor
as a convenient abstraction:
from concurrent.futures import ProcessPoolExecutor
def worker(procnum):
'''worker function'''
print(str(procnum) + ' represent!')
return procnum
if __name__ == '__main__':
with ProcessPoolExecutor() as executor:
print(list(executor.map(worker, range(5))))
Output:
0 represent!
1 represent!
2 represent!
3 represent!
4 represent!
[0, 1, 2, 3, 4]
A solution that works with inherited classes too:
from itertools import chain
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class Mixin(object):
def as_dict(self):
tables = [base.__table__ for base in self.__class__.__bases__ if base not in [Base, Mixin]]
tables.append(self.__table__)
return {c.name: getattr(self, c.name) for c in chain.from_iterable([x.columns for x in tables])}
We can copy all columns from one table to another, existing table:
INSERT INTO table2 SELECT * FROM table1;
Or we can copy only the columns we want to into another, existing table:
INSERT INTO table2 (column_name(s)) SELECT column_name(s) FROM table1;
or SELECT * INTO BACKUP_TABLE1 FROM TABLE1
Uncomment the line extension=php_mysql.dll
in your "php.ini" file and restart Apache.
Additionally, "libmysql.dll" file must be available to Apache, i.e., it must be either in available in Windows systems PATH or in Apache working directory.
See more about installing MySQL extension in manual.
P.S. I would advise to consider MySQL extension as deprecated and to use MySQLi or even PDO for working with databases (I prefer PDO).
You can use stored procedure in this way..
DELIMITER |
CREATE PROCEDURE explode( pDelim VARCHAR(32), pStr TEXT)
BEGIN
DROP TABLE IF EXISTS temp_explode;
CREATE TEMPORARY TABLE temp_explode (id INT AUTO_INCREMENT PRIMARY KEY NOT NULL, word VARCHAR(40));
SET @sql := CONCAT('INSERT INTO temp_explode (word) VALUES (', REPLACE(QUOTE(pStr), pDelim, '\'), (\''), ')');
PREPARE myStmt FROM @sql;
EXECUTE myStmt;
END |
DELIMITER ;
example call:
SET @str = "The quick brown fox jumped over the lazy dog";
SET @delim = " ";
CALL explode(@delim,@str);
SELECT id,word FROM temp_explode;
You could read Google answer for it here: http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Preincrement_and_Predecrement
So, main point is, what no difference for simple object, but for iterators and other template objects you should use preincrement.
EDITED:
There are no difference because you use simple type, so no side effects, and post- or preincrements executed after loop body, so no impact on value in loop body.
You could check it with such a loop:
for (int i = 0; i < 5; cout << "we still not incremented here: " << i << endl, i++)
{
cout << "inside loop body: " << i << endl;
}
Try to use this code to handle server disconnect:
var db_config = {
host: 'localhost',
user: 'root',
password: '',
database: 'example'
};
var connection;
function handleDisconnect() {
connection = mysql.createConnection(db_config); // Recreate the connection, since
// the old one cannot be reused.
connection.connect(function(err) { // The server is either down
if(err) { // or restarting (takes a while sometimes).
console.log('error when connecting to db:', err);
setTimeout(handleDisconnect, 2000); // We introduce a delay before attempting to reconnect,
} // to avoid a hot loop, and to allow our node script to
}); // process asynchronous requests in the meantime.
// If you're also serving http, display a 503 error.
connection.on('error', function(err) {
console.log('db error', err);
if(err.code === 'PROTOCOL_CONNECTION_LOST') { // Connection to the MySQL server is usually
handleDisconnect(); // lost due to either server restart, or a
} else { // connnection idle timeout (the wait_timeout
throw err; // server variable configures this)
}
});
}
handleDisconnect();
In your code i am missing the parts after connection = mysql.createConnection(db_config);
The two above it is not run.
The table edit button:
<a data-toggle="modal" type="edit" id="{{$b->id}}" data-id="{{$b->id}}" data-target="#form_edit_masterbank" data-bank_nama="{{ $b->bank_nama }}" data-bank_accnama="{{ $b->bank_accnama }}" data-bank_accnum="{{ $b->bank_accnum }}" data-active="{{ $b->active }}" data-logobank="{{asset('components/images/user/masterbank/')}}/{{$b->images}}" href="#" class="edit edit-masterbank" ><i class="fa fa-edit" ></i></a>
and then in JavaScript:
$('.imagepreview555').attr('src', logobank);
and then in HTML:
<img src="" class="imagepreview555" style="width: 100%;" />
Not it runs.
I found this article
/// <summary>
/// Creates a new Image containing the same image only rotated
/// </summary>
/// <param name=""image"">The <see cref=""System.Drawing.Image"/"> to rotate
/// <param name=""offset"">The position to rotate from.
/// <param name=""angle"">The amount to rotate the image, clockwise, in degrees
/// <returns>A new <see cref=""System.Drawing.Bitmap"/"> of the same size rotated.</see>
/// <exception cref=""System.ArgumentNullException"">Thrown if <see cref=""image"/">
/// is null.</see>
public static Bitmap RotateImage(Image image, PointF offset, float angle)
{
if (image == null)
throw new ArgumentNullException("image");
//create a new empty bitmap to hold rotated image
Bitmap rotatedBmp = new Bitmap(image.Width, image.Height);
rotatedBmp.SetResolution(image.HorizontalResolution, image.VerticalResolution);
//make a graphics object from the empty bitmap
Graphics g = Graphics.FromImage(rotatedBmp);
//Put the rotation point in the center of the image
g.TranslateTransform(offset.X, offset.Y);
//rotate the image
g.RotateTransform(angle);
//move the image back
g.TranslateTransform(-offset.X, -offset.Y);
//draw passed in image onto graphics object
g.DrawImage(image, new PointF(0, 0));
return rotatedBmp;
}
For your purpose, you can just use
position: absolute;
top: 0%;
and it still be resizable, scrollable and responsive.
Just a follow-up to dbb's accepted answer: Rather than adding the immediate cell on the right to the selection, why not select a cell way off the working range (i.e. a dummy cell that you know the user will never need). In the following code cell ZZ1
is the dummy cell
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Application.EnableEvents = False
Union(Target, Me.Range("ZZ1")).Select
Application.EnableEvents = True
' Respond to click/selection-change here
End Sub
Spring beans are just instance objects that are managed by the Spring container, namely, they are created and wired by the framework and put into a "bag of objects" (the container) from where you can get them later.
The "wiring" part there is what dependency injection is all about, what it means is that you can just say "I will need this thing" and the framework will follow some rules to get you the proper instance.
For someone who isn't used to Spring, I think Wikipedia Spring's article has a nice description:
Central to the Spring Framework is its inversion of control container, which provides a consistent means of configuring and managing Java objects using reflection. The container is responsible for managing object lifecycles of specific objects: creating these objects, calling their initialization methods, and configuring these objects by wiring them together.
Objects created by the container are also called managed objects or beans. The container can be configured by loading XML files or detecting specific Java annotations on configuration classes. These data sources contain the bean definitions which provide the information required to create the beans.
Objects can be obtained by means of either dependency lookup or dependency injection. Dependency lookup is a pattern where a caller asks the container object for an object with a specific name or of a specific type. Dependency injection is a pattern where the container passes objects by name to other objects, via either constructors, properties, or factory methods.
You should check that fractional part of the number is 0. Use
x==Math.ceil(x)
or
x==Math.round(x)
or something like that
I'll leave this for further visitors as for me it was something about the main thread being unable to System.out.println
.
public class LogUtil {
private static String log = "";
private static boolean started = false;
public static void print(String s) {
//Start the thread unless it's already running
if(!started) {
start();
}
//Append a String to the log
log += s;
}
public static void println(String s) {
//Start the thread unless it's already running
if(!started) {
start();
}
//Append a String to the log with a newline.
//NOTE: Change to print(s + "\n") if you don't want it to trim the last newline.
log += (s.endsWith("\n") )? s : (s + "\n");
}
private static void start() {
//Creates a new Thread responsible for showing the logs.
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
while(true) {
//Execute 100 times per second to save CPU cycles.
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
//If the log variable has any contents...
if(!log.isEmpty()) {
//...print it and clear the log variable for new data.
System.out.print(log);
log = "";
}
}
}
});
thread.start();
started = true;
}
}
Usage: LogUtil.println("This is a string");
int dp1 = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 1,
context.getResources().getDisplayMetrics());
tv.setLayoutParams(new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
dp1 * 100)); // if you want to set layout height to 100dp
llview.addView(tv);
This maybe irrelevant and of no use, but as it's javascript, you don't have to use the ternary as suggested above in the ng-click statement. You should also be able to use the lazy evaluation ("or die") syntax as well. So for your example above:
<input ng-click="{{if(profileForm.$valid) updateMyProfile()}}" name="submit" id="submit" value="Save" class="submit" type="submit">
would become:
<input ng-click="profileForm.$valid && updateMyProfile()" name="submit" id="submit" value="Save" class="submit" type="submit">
In this case, if the profile is not valid then nothing happens, otherwise, updateMyProfile() is called. Like in the link @falinsky provides above.
I recently wrote this code to find the sum of numbers. It can be easily modified to find if a number is prime or not instead. Benchmarks are on top of the code.
// built on core-i2 e8400
// Benchmark from PowerShell
// Measure-Command { ExeName.exe }
// Days : 0
// Hours : 0
// Minutes : 0
// Seconds : 23
// Milliseconds : 516
// Ticks : 235162598
// TotalDays : 0.00027217893287037
// TotalHours : 0.00653229438888889
// TotalMinutes : 0.391937663333333
// TotalSeconds : 23.5162598
// TotalMilliseconds : 23516.2598
// built with latest MSVC
// cl /EHsc /std:c++latest main.cpp /O2 /fp:fast /Qpar
#include <cmath>
#include <iostream>
#include <vector>
inline auto prime = [](std::uint64_t I, std::vector<std::uint64_t> &cache) -> std::uint64_t {
std::uint64_t root{static_cast<std::uint64_t>(std::sqrtl(I))};
for (std::size_t i{}; cache[i] <= root; ++i)
if (I % cache[i] == 0)
return 0;
cache.push_back(I);
return I;
};
inline auto prime_sum = [](std::uint64_t S) -> std::uint64_t {
std::uint64_t R{5};
std::vector<std::uint64_t> cache;
cache.reserve(S / 16);
cache.push_back(3);
for (std::uint64_t I{5}; I <= S; I += 8)
{
std::uint64_t U{I % 3};
if (U != 0)
R += prime(I, cache);
if (U != 1)
R += prime(I + 2, cache);
if (U != 2)
R += prime(I + 4, cache);
R += prime(I + 6, cache);
}
return R;
};
int main()
{
std::cout << prime_sum(63210123);
}
This is the lazy and dangerous way to synchronize a directory with SVN including new files:
svn rm --keep-local dir
svn add dir
Although this can work in a pinch it can have serious consequences as well. For example, SVN will often lose track of a file's history.
The ideal way to syncronize a directory would be to be able to diff then use svn patch, however this deviates from formats in the diff command and the svn diff command will compare working directory differences rather than differences on the file system level.
You have to get back out of the Iframe with the following code:
driver.switchTo().frame(driver.findElement(By.id("frameId")));
//do your stuff
driver.switchTo().defaultContent();
hope that helps
You can use either = or "space". For instance following two commands return the same
git log --author="Developer1"
git log --author "Developer1"
this is how you do it with ActionLIstener
import java.awt.FlowLayout;
import java.awt.event.*;
import javax.swing.*;
public class MyWind extends JFrame{
public MyWind() {
initialize();
}
private void initialize() {
setSize(300, 300);
setLayout(new FlowLayout(FlowLayout.LEFT));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JTextField field = new JTextField();
field.setSize(200, 50);
field.setText(" ");
JComboBox comboBox = new JComboBox();
comboBox.setEditable(true);
comboBox.addItem("item1");
comboBox.addItem("item2");
//
// Create an ActionListener for the JComboBox component.
//
comboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
//
// Get the source of the component, which is our combo
// box.
//
JComboBox comboBox = (JComboBox) event.getSource();
Object selected = comboBox.getSelectedItem();
if(selected.toString().equals("item1"))
field.setText("30");
else if(selected.toString().equals("item2"))
field.setText("40");
}
});
getContentPane().add(comboBox);
getContentPane().add(field);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new MyWind().setVisible(true);
}
});
}
}
Don't make it an Array if it is not an Array, make it an object:
var saveData = {};
saveData.a = 2;
saveData.c = 1;
// equivalent to...
var saveData = {a: 2, c: 1}
// equivalent to....
var saveData = {};
saveData['a'] = 2;
saveData['c'] = 1;
Doing it the way you are doing it with Arrays is just taking advantage of Javascript's treatment of Arrays and not really the right way of doing it.
The following will allow you to get at both the key and value at the same time.
foreach ($arr as $key => $value)
{
echo($key);
}
JAR File Manifest Attributes for Security
The JAR file manifest contains information about the contents of the JAR file, including security and configuration information.
Add the attributes to the manifest before the JAR file is signed.
See Modifying a Manifest File in the Java Tutorial for information on adding attributes to the JAR manifest file.
Permissions Attribute
The Permissions attribute is used to verify that the permissions level requested by the RIA when it runs matches the permissions level that was set when the JAR file was created.
Use this attribute to help prevent someone from re-deploying an application that is signed with your certificate and running it at a different privilege level. Set this attribute to one of the following values:
sandbox - runs in the security sandbox and does not require additional permissions.
all-permissions - requires access to the user's system resources.
Changes to Security Slider:
The following changes to Security Slider were included in this release(7u51):
For more information, see Java Control Panel documentation.
sample MANIFEST.MF
Manifest-Version: 1.0
Ant-Version: Apache Ant 1.8.3
Created-By: 1.7.0_51-b13 (Oracle Corporation)
Trusted-Only: true
Class-Path: lib/plugin.jar
Permissions: sandbox
Codebase: http://myweb.de http://www.myweb.de
Application-Name: summary-applet
Java's parser in java.net.URI
is going to fail if the URI isn't fully encoded to its standards. For example, try to parse: http://www.google.com/search?q=cat|dog
. An exception will be thrown for the vertical bar.
urllib makes it easy to convert a string to a java.net.URI
. It will pre-process and escape the URL.
assertEquals("http://www.google.com/search?q=cat%7Cdog",
Urls.createURI("http://www.google.com/search?q=cat|dog").toString());
Martijen's answer makes sense, but it was missing something crucial that may seem obvious to others but was hard for me to figure out.
In the version where you use argparse, you need to have this line in the main body.
args = parser.parse_args(args)
Normally when you are using argparse just in a script you just write
args = parser.parse_args()
and parse_args find the arguments from the command line. But in this case the main function does not have access to the command line arguments, so you have to tell argparse what the arguments are.
Here is an example
import argparse
import sys
def x(x_center, y_center):
print "X center:", x_center
print "Y center:", y_center
def main(args):
parser = argparse.ArgumentParser(description="Do something.")
parser.add_argument("-x", "--xcenter", type=float, default= 2, required=False)
parser.add_argument("-y", "--ycenter", type=float, default= 4, required=False)
args = parser.parse_args(args)
x(args.xcenter, args.ycenter)
if __name__ == '__main__':
main(sys.argv[1:])
Assuming you named this mytest.py To run it you can either do any of these from the command line
python ./mytest.py -x 8
python ./mytest.py -x 8 -y 2
python ./mytest.py
which returns respectively
X center: 8.0
Y center: 4
or
X center: 8.0
Y center: 2.0
or
X center: 2
Y center: 4
Or if you want to run from another python script you can do
import mytest
mytest.main(["-x","7","-y","6"])
which returns
X center: 7.0
Y center: 6.0
In Java:
String str = " hello world ";
// prints "hello world"
System.out.println(str.replaceAll("^(\\s+)|(\\s+)$", ""));
From your question, you are running python2.7 and Cygwin.
Python should be installed for windows, which from your question it seems it is. If "which python" prints out /usr/bin/python , then from the bash prompt you are running the cygwin version.
Set the Python Environmental variables appropriately , for instance in my case:
PY_HOME=C:\opt\Python27
PYTHONPATH=C:\opt\Python27;c:\opt\Python27\Lib
In that case run cygwin setup and uninstall everything python. After that run "which pydoc", if it shows
/usr/bin/pydoc
Replace /usr/bin/pydoc with
#! /bin/bash
/cygdrive/c/WINDOWS/system32/cmd /c %PYTHONHOME%\Scripts\\pydoc.bat
Then add this to $PY_HOME/Scripts/pydoc.bat
rem wrapper for pydoc on Win32
@python c:\opt\Python27\Lib\pydoc.py %*
Now when you type in the cygwin bash prompt you should see:
$ pydoc
pydoc - the Python documentation tool
pydoc.py <name> ...
Show text documentation on something. <name>
may be the name of a Python keyword, topic,
function, module, or package, or a dotted
reference to a class or function within a
module or module in a package.
...
Many way to Json Parse but i have found most effective way to
@model List<string[]>
<script>
function DataParse() {
var model = '@Html.Raw(Json.Encode(Model))';
var data = JSON.parse(model);
for (i = 0; i < data.length; i++) {
......
}
</script>
after you connect server and you want to connect on your host, you should do the steps below:
GRANT ALL ON . to root@'write_your_ip_addres' IDENTIFIED BY 'write_password_to_connect'
;nano /etc/mysql/my.cnf
service mysql restart
What you're looking for is technically known as currying.
function getMyCallback(randomValue)
{
return function(otherParam)
{
return randomValue * otherParam //or whatever it is you are doing.
}
}
var myCallback = getMyCallBack(getRand())
alert(myCallBack(1));
alert(myCallBack(2));
The above isn't exactly a curried function but it achieves the result of maintaining an existing value without adding variables to the global namespace or requiring some other object repository for it.
It depends on wether the locatoin is detected by different DNS resolution from different locations, or by IP address that you are browsing from.
If its by DNS, you could just modify your hosts file to point at the server used in europe. Get your friend to ping the address, to see if its different from the one yours resolves to.
To browse from a different IP address:
You can rent a VPS server. You can use putty / SSH to act as a proxy. I use this from time to time to brows from the US using a VPS server I rent in the US.
Having an account on a remote host may or may not be enough. Sadly, my dreamhost account, even though I have ssh access, does not allow proxying.
The ?
is an unnamed parameter which can be filled in by a program running the query to avoid SQL injection.
The reason your URL is being rewritten to file///K:/AmberCRO%20SOP/2011-07-05/SOP-SOP-3.0.pdf
is because you specified http://file://
The http://
at the beginning is the protocol being used, and your browser is stripping out the second colon (:) because it is invalid.
Note
If you link to something like
<a href="file:///K:/yourfile.pdf">yourfile.pdf</a>
The above represents a link to a file called k:/yourfile.pdf
on the k: drive on the machine on which you are viewing the URL.
You can do this, for example the below creates a link to C:\temp\test.pdf
<a href="file:///C:/Temp/test.pdf">test.pdf</a>
By specifying file:// you are indicating that this is a local resource. This resource is NOT on the internet.
Most people do not have a K:/ drive.
But, if this is what you are trying to achieve, that's fine, but this is not how a "typical" link on a web page works, and you shouldn't being doing this unless everyone who is going to access your link has access to the (same?) K:/drive (this might be the case with a shared network drive).
You could try
<a href="file:///K:/AmberCRO-SOP/2011-07-05/SOP-SOP-3.0.pdf">test.pdf</a>
<a href="AmberCRO-SOP/2011-07-05/SOP-SOP-3.0.pdf">test.pdf</a>
<a href="2011-07-05/SOP-SOP-3.0.pdf">test.pdf</a>
Note that http://file:///K:/AmberCRO%20SOP/2011-07-05/SOP-SOP-3.0.pdf
is a malformed
In xcode 11.1 swift 5.0
select the code you would like to add block comment then press ? + ? + /
This is the cleanest way... BY FAR:
Public Function IsDir(s) As Boolean
IsDir = CreateObject("Scripting.FileSystemObject").FolderExists(s)
End Function
Working off of Jarod's solution and the issue brought up by Jeffiekins, you could modify
"May 16, 2011"
to
"=""May 16, 2011"""
If you want to replace a fragment with another, you should have added them dynamically, first of all. Fragments that are hard coded in XML, cannot be replaced.
// Create new fragment and transaction
Fragment newFragment = new ExampleFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
Refer this post: Replacing a fragment with another fragment inside activity group
This question is rooted in branch prediction models on CPUs. I'd recommend reading this paper:
Increasing the Instruction Fetch Rate via Multiple Branch Prediction and a Branch Address Cache
When you have sorted elements, the IR can not be bothered to fetch all CPU instructions, again and again. It fetches them from the cache.
react-tidy
has a custom hook just for doing that called useRefresh
:
import React from 'react'
import {useRefresh} from 'react-tidy'
function App() {
const refresh = useRefresh()
return (
<p>
The time is {new Date()} <button onClick={refresh}>Refresh</button>
</p>
)
}
Disclaimer I am the writer of this library.
In Express 4.x you can use req.hostname
, which returns the domain name, without port. i.e.:
// Host: "example.com:3000"
req.hostname
// => "example.com"
In version r82 of Three.js TextureLoader is the object to use for loading a texture.
Extract (test.js):
var scene = new THREE.Scene();
var ratio = window.innerWidth / window.innerHeight;
var camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight,
0.1, 50);
var renderer = ...
[...]
/**
* Will be called when load completes.
* The argument will be the loaded texture.
*/
var onLoad = function (texture) {
var objGeometry = new THREE.BoxGeometry(20, 20, 20);
var objMaterial = new THREE.MeshPhongMaterial({
map: texture,
shading: THREE.FlatShading
});
var mesh = new THREE.Mesh(objGeometry, objMaterial);
scene.add(mesh);
var render = function () {
requestAnimationFrame(render);
mesh.rotation.x += 0.010;
mesh.rotation.y += 0.010;
renderer.render(scene, camera);
};
render();
}
// Function called when download progresses
var onProgress = function (xhr) {
console.log((xhr.loaded / xhr.total * 100) + '% loaded');
};
// Function called when download errors
var onError = function (xhr) {
console.log('An error happened');
};
var loader = new THREE.TextureLoader();
loader.load('texture.jpg', onLoad, onProgress, onError);
In this example the textures are loaded inside the constructor of the mesh, multiple texture are loaded using Promises.
Extract (Globe.js):
Create a new container using Object3D
for having two meshes in the same container:
var Globe = function (radius, segments) {
THREE.Object3D.call(this);
this.name = "Globe";
var that = this;
// instantiate a loader
var loader = new THREE.TextureLoader();
A map called textures
where every object contains the url
of a texture file and val
for storing the value of a Three.js texture object.
// earth textures
var textures = {
'map': {
url: 'relief.jpg',
val: undefined
},
'bumpMap': {
url: 'elev_bump_4k.jpg',
val: undefined
},
'specularMap': {
url: 'wateretopo.png',
val: undefined
}
};
The array of promises, for each object in the map called textures
push a new Promise in the array texturePromises
, every Promise will call loader.load
. If the value of entry.val
is a valid THREE.Texture
object, then resolve the promise.
var texturePromises = [], path = './';
for (var key in textures) {
texturePromises.push(new Promise((resolve, reject) => {
var entry = textures[key]
var url = path + entry.url
loader.load(url,
texture => {
entry.val = texture;
if (entry.val instanceof THREE.Texture) resolve(entry);
},
xhr => {
console.log(url + ' ' + (xhr.loaded / xhr.total * 100) +
'% loaded');
},
xhr => {
reject(new Error(xhr +
'An error occurred loading while loading: ' +
entry.url));
}
);
}));
}
Promise.all
takes the promise array texturePromises
as argument. Doing so makes the browser wait for all the promises to resolve, when they do we can load the geometry and the material.
// load the geometry and the textures
Promise.all(texturePromises).then(loadedTextures => {
var geometry = new THREE.SphereGeometry(radius, segments, segments);
var material = new THREE.MeshPhongMaterial({
map: textures.map.val,
bumpMap: textures.bumpMap.val,
bumpScale: 0.005,
specularMap: textures.specularMap.val,
specular: new THREE.Color('grey')
});
var earth = that.earth = new THREE.Mesh(geometry, material);
that.add(earth);
});
For the cloud sphere only one texture is necessary:
// clouds
loader.load('n_amer_clouds.png', map => {
var geometry = new THREE.SphereGeometry(radius + .05, segments, segments);
var material = new THREE.MeshPhongMaterial({
map: map,
transparent: true
});
var clouds = that.clouds = new THREE.Mesh(geometry, material);
that.add(clouds);
});
}
Globe.prototype = Object.create(THREE.Object3D.prototype);
Globe.prototype.constructor = Globe;