C++ programs are translated to assembly programs during the generation of machine code from the source code. It would be virtually wrong to say assembly is slower than C++. Moreover, the binary code generated differs from compiler to compiler. So a smart C++ compiler may produce binary code more optimal and efficient than a dumb assembler's code.
However I believe your profiling methodology has certain flaws. The following are general guidelines for profiling:
Note : This answer is now out-of-date. You are now required to have an API key to use google maps. Read More
you need to change your API from V2 to V3, Since Google Map Version 3 don't required API Key
Check this out..
write your script
as
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
They serve the actual image inside CSS so there will be less HTTP requests per page.
Jerryf's answer is fine, except for one flaw.
The onload event should be set before the src. Sometimes the src can be loaded instantly and never fire the onload event.
(Like Totty.js pointed out.)
var canvas = document.getElementById("c");
var ctx = canvas.getContext("2d");
var image = new Image();
image.onload = function() {
ctx.drawImage(image, 0, 0);
};
image.src = "data:image/ png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAIAAAACDbGyAAAAAXNSR0IArs4c6QAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9oMCRUiMrIBQVkAAAAZdEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAADElEQVQI12NgoC4AAABQAAEiE+h1AAAAAElFTkSuQmCC";
You can utilize the dependency management mechanism.
If you create entries in the <dependencyManagement> section of your pom for spring-security-web and spring-web with the desired 3.1.0 version set the managed version of the artifact will override those specified in the transitive dependency tree.
I'm not sure if that really saves you any code, but it is a cleaner solution IMO.
It appears they do not want to support the syntax from ng1.
According to Miško Hevery (reference):
Maps have no orders in keys and hence they iteration is unpredictable. This was supported in ng1, but we think it was a mistake and will not be supported in NG2
The plan is to have a mapToIterable pipe
<div *ngFor"var item of map | mapToIterable">
So in order to iterate over your object you will need to use a "pipe". Currently there is no pipe implemented that does that.
As a workaround, here is a small example that iterates over the keys:
Component:
import {Component} from 'angular2/core';
@Component({
selector: 'component',
templateUrl: `
<ul>
<li *ngFor="#key of keys();">{{key}}:{{myDict[key]}}</li>
</ul>
`
})
export class Home {
myDict : Dictionary;
constructor() {
this.myDict = {'key1':'value1','key2':'value2'};
}
keys() : Array<string> {
return Object.keys(this.myDict);
}
}
interface Dictionary {
[ index: string ]: string
}
Why unicode? Because ASCII has just 127 characters. Those from 128 to 255 differ in different countries, that's why there are codepages. So they said lets have up to 1114111 characters. So how do you store the highest codepoint? You'll need to store it using 21 bits, so you'll use a DWORD having 32 bits with 11 bits wasted. So if you use a DWORD to store a unicode character, it is the easiest way because the value in your DWORD matches exactly the codepoint. But DWORD arrays are of course larger than WORD arrays and of course even larger than BYTE arrays. That's why there is not only utf-32, but also utf-16. But utf-16 means a WORD stream, and a WORD has 16 bits so how can the highest codepoint 1114111 fit into a WORD? It cannot! So they put everyything higher than 65535 into a DWORD which they call a surrogate-pair. Such surrogate-pair are two WORDS and can get detected by looking at the first 6 bits. So what about utf-8? It is a byte array or byte stream, but how can the highest codepoint 1114111 fit into a byte? It cannot! Okay, so they put in also a DWORD right? Or possibly a WORD, right? Almost right! They invented utf-8 sequences which means that every codepoint higher than 127 must get encoded into a 2-byte, 3-byte or 4-byte sequence. Wow! But how can we detect such sequences? Well, everything up to 127 is ASCII and is a single byte. What starts with 110 is a two-byte sequence, what starts with 1110 is a three-byte sequence and what starts with 11110 is a four-byte sequence. The remaining bits of these so called "startbytes" belong to the codepoint. Now depending on the sequence, following bytes must follow. A following byte starts with 10, the remaining bits are 6 bits of payload bits and belong to the codepoint. Concatenate the payload bits of the startbyte and the following byte/s and you'll have the codepoint. That's all the magic of utf-8.
If you'd like a simple method to resolve this problem. (Can be used as an extension)
See below:
public static string RemoveFirstInstanceOfString(this string value, string removeString)
{
int index = value.IndexOf(removeString, StringComparison.Ordinal);
return index < 0 ? value : value.Remove(index, removeString.Length);
}
Usage:
string valueWithPipes = "| 1 | 2 | 3";
string valueWithoutFirstpipe = valueWithPipes.RemoveFirstInstanceOfString("|");
//Output, valueWithoutFirstpipe = " 1 | 2 | 3";
Inspired by and modified @LukeH's and @Mike's answer.
Don't forget the StringComparison.Ordinal to prevent issues with Culture settings. https://www.jetbrains.com/help/resharper/2018.2/StringIndexOfIsCultureSpecific.1.html
Try position:sticky on parent div of the element you want to be fixed.
More info here: http://html5-demos.appspot.com/static/css/sticky.html. Caution: Check for browser version compatibility.
Try the following code to find the optimal camera position
Use print to get the camera positions
def move_view(event):
ax.autoscale(enable=False, axis='both')
koef = 8
zkoef = (ax.get_zbound()[0] - ax.get_zbound()[1]) / koef
xkoef = (ax.get_xbound()[0] - ax.get_xbound()[1]) / koef
ykoef = (ax.get_ybound()[0] - ax.get_ybound()[1]) / koef
## Map an motion to keyboard shortcuts
if event.key == "ctrl+down":
ax.set_ybound(ax.get_ybound()[0] + xkoef, ax.get_ybound()[1] + xkoef)
if event.key == "ctrl+up":
ax.set_ybound(ax.get_ybound()[0] - xkoef, ax.get_ybound()[1] - xkoef)
if event.key == "ctrl+right":
ax.set_xbound(ax.get_xbound()[0] + ykoef, ax.get_xbound()[1] + ykoef)
if event.key == "ctrl+left":
ax.set_xbound(ax.get_xbound()[0] - ykoef, ax.get_xbound()[1] - ykoef)
if event.key == "down":
ax.set_zbound(ax.get_zbound()[0] - zkoef, ax.get_zbound()[1] - zkoef)
if event.key == "up":
ax.set_zbound(ax.get_zbound()[0] + zkoef, ax.get_zbound()[1] + zkoef)
# zoom option
if event.key == "alt+up":
ax.set_xbound(ax.get_xbound()[0]*0.90, ax.get_xbound()[1]*0.90)
ax.set_ybound(ax.get_ybound()[0]*0.90, ax.get_ybound()[1]*0.90)
ax.set_zbound(ax.get_zbound()[0]*0.90, ax.get_zbound()[1]*0.90)
if event.key == "alt+down":
ax.set_xbound(ax.get_xbound()[0]*1.10, ax.get_xbound()[1]*1.10)
ax.set_ybound(ax.get_ybound()[0]*1.10, ax.get_ybound()[1]*1.10)
ax.set_zbound(ax.get_zbound()[0]*1.10, ax.get_zbound()[1]*1.10)
# Rotational movement
elev=ax.elev
azim=ax.azim
if event.key == "shift+up":
elev+=10
if event.key == "shift+down":
elev-=10
if event.key == "shift+right":
azim+=10
if event.key == "shift+left":
azim-=10
ax.view_init(elev= elev, azim = azim)
# print which ever variable you want
ax.figure.canvas.draw()
fig.canvas.mpl_connect("key_press_event", move_view)
plt.show()
You can also set the title of your chart by adding the title parameter as follows
ax.set(xlabel='common xlabel', ylabel='common ylabel', title='some title')
try:
r = requests.post(url, data=data, verify='/path/to/public_key.pem')
You probably just want
git branch --contains branch-to-delete
This will list all branches which contain the commits from "branch-to-delete". If it reports more than just "branch-to-delete", the branch has been merged.
Your alternatives are really just rev-list syntax things. e.g. git log one-branch..another-branch
shows everything that one-branch
needs to have everything another-branch
has.
You may also be interested in git show-branch
as a way to see what's where.
Use (eventName)
for while binding event to DOM, basically ()
is used for event binding. Also use ngModel
to get two way binding for myModel
variable.
Markup
<input type="text" [(ngModel)]="myModel" (blur)="onBlurMethod()">
Code
export class AppComponent {
myModel: any;
constructor(){
this.myModel = '123';
}
onBlurMethod(){
alert(this.myModel)
}
}
Alternative(not preferable)
<input type="text" #input (blur)="onBlurMethod($event.target.value)">
For model driven form to fire validation on blur
, you could pass updateOn
parameter.
ctrl = new FormControl('', {
updateOn: 'blur', //default will be change
validators: [Validators.required]
});
For multiple shell commands, I ignores the failures by adding:
set +e
commands
true
There was an error in understanding of return Type Just add Header and it will solve your problem
@Headers("Content-Type: application/json")
The problem must be with the value Model.Id which is null. You can confirm by assigning a value, e.g
@{
var blogPostId = 1;
}
If the error disappers, then u need to make sure that your model Id has a value before passing it to the view
Try the export function of phpMyAdmin.
I think there is also a possibility to copy the database files from one server to another, but I do not have a server available at the moment so I can't test it.
I would suggest you read the appropriate sections in The Java Tutorial from Sun:
http://java.sun.com/docs/books/tutorial/getStarted/cupojava/win32.html
varbinary(max)
is the way to go (introduced in SQL Server 2005)
Since PHP/5.4.0, there is an option called JSON_UNESCAPED_UNICODE
. Check it out:
https://php.net/function.json-encode
Therefore you should try:
json_encode( $text, JSON_UNESCAPED_UNICODE );
If I understand correctly. In order to group your results as requested, your Group By clause needs to have the same expression as your select statement.
GROUP BY MONTH(date) + '.' + YEAR(date)
To display the date as "month-date" format change the '.' to '-' The full syntax would be something like this.
SELECT MONTH(date) + '-' + YEAR(date) AS Mjesec, SUM(marketingExpense) AS
SumaMarketing, SUM(revenue) AS SumaZarada
FROM [Order]
WHERE (idCustomer = 1) AND (date BETWEEN '2001-11-3' AND '2011-11-3')
GROUP BY MONTH(date) + '.' + YEAR(date)
Poor man's configuration file:
Add to your index.html as first líne in the body tag:
<script lang="javascript" src="assets/config.js"></script>
Add assets/config.js:
var config = {
apiBaseUrl: "http://localhost:8080"
}
Add config.ts:
export const config: AppConfig = window['config']
export interface AppConfig {
apiBaseUrl: string
}
You see the two empty -D
entries in the g++
command line? They're causing the problem. You must have values in the -D
items e.g. -DWIN32
if you're insistent on using something like -D$(SYSTEM) -D$(ENVIRONMENT) then you can use something like:
SYSTEM ?= generic
ENVIRONMENT ?= generic
in the makefile which gives them default values.
Your output looks to be missing the all important output:
<command-line>:0:1: error: macro names must be identifiers
<command-line>:0:1: error: macro names must be identifiers
just to clarify, what actually got sent to g++
was -D -DWindows_NT
, i.e. define a preprocessor macro called -DWindows_NT
; which is of course not a valid identifier (similarly for -D -I.
)
Semantically what you are trying is invalid html, table
element cannot have a div
element as a direct child. What you can do is, get your div
element inside a td
element and than try to hide it
It must be because of commit is ahead of your current push.
git pull origin "name of branch you want to push"
git rebase
If git rebase is successful, then good. Otherwise, you have resolve all merge conflicts locally and keep it continuing until rebase with remote is successful.
git rebase --continue
if list item view contains button or checkbox or imagebutton, the onitemclicklistener and onitemlongclicklistener not working due to it has own onclick listener.
set focusable as false
holder.button.setFocusable(false);
In this example, you may show your menu centered.
<div id="main-menu-container">
<div id="main-menu">
//your menu
</div>
</div>
.f-nav{ /* To fix main menu container */
z-index: 9999;
position: fixed;
left: 0;
top: 0;
width: 100%;
}
#main-menu-container {
text-align: center; /* Assuming your main layout is centered */
}
#main-menu {
display: inline-block;
width: 1024px; /* Your menu's width */
}
$("document").ready(function($){
var nav = $('#main-menu-container');
$(window).scroll(function () {
if ($(this).scrollTop() > 125) {
nav.addClass("f-nav");
} else {
nav.removeClass("f-nav");
}
});
});
The RFC is just trying to say that a signed integer is a normal 4-byte integer with bytes ordered in a big-endian way.
Now, you are most probably working on a little-endian machine and BitConverter.GetBytes()
will give you the byte[]
reversed. So you could try:
int intValue;
byte[] intBytes = BitConverter.GetBytes(intValue);
Array.Reverse(intBytes);
byte[] result = intBytes;
For the code to be most portable, however, you can do it like this:
int intValue;
byte[] intBytes = BitConverter.GetBytes(intValue);
if (BitConverter.IsLittleEndian)
Array.Reverse(intBytes);
byte[] result = intBytes;
The answer is: you can't only through sms, i have tried that approach before.
You could fetch the base station IDs, but this won't help you a lot without the location of the base station itself and this informations are really hard to retrieve from the providers.
I have looked through the 3 apps you have listed in your question:
For the lazy and the learning, to put it into your theme, Rfvgyhn's full code
<?php $category = get_the_category();
$firstCategory = $category[0]->cat_name; echo $firstCategory;?>
ALTER TABLE Employee ADD DEFAULT 'SANDNES' FOR CityBorn
There is a difference between length of String
and array
to clarify:
int a[] = {1, 2, 3, 4};
String s = "1234";
a.length //gives the length of the array
s.length() //gives the length of the string
String filePath = Environment.getExternalStorageDirectory()+"/yourfolderNAme/yopurfile.mp3";
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(filePath);
mediaPlayer.prepare();
mediaPlayer.start()
and this play from raw folder.
int resID = myContext.getResources().getIdentifier(playSoundName,"raw",myContext.getPackageName());
MediaPlayer mediaPlayer = MediaPlayer.create(myContext,resID);
mediaPlayer.prepare();
mediaPlayer.start();
mycontext=application.this. use.
Not quite, the AND has to be lower-case.
<xsl:when test="4 < 5 and 1 < 2">
<!-- do something -->
</xsl:when>
Based on @blushrt 's great answer I will update this response. Just using -
$("#Select_ID").val(id);
works if you've preloaded everything you need to the selector.
In My case @uncaught_exceptions's answer didn't work, I had to use List.class
instead of java.lang.reflect.Type
:
String jsonDuplicatedItems = request.getSession().getAttribute("jsonDuplicatedItems").toString();
List<Map.Entry<Product, Integer>> entries = gson.fromJson(jsonDuplicatedItems, List.class);
Yes, you can download the IP address ranges by country from https://lite.ip2location.com/ip-address-ranges-by-country
You can see that each country has multiple ranges and changes frequently.
You can't use UIImagePickerController
, but you can use a custom image picker. I think ELCImagePickerController
is the best option, but here are some other libraries you could use:
Objective-C
1. ELCImagePickerController
2. WSAssetPickerController
3. QBImagePickerController
4. ZCImagePickerController
5. CTAssetsPickerController
6. AGImagePickerController
7. UzysAssetsPickerController
8. MWPhotoBrowser
9. TSAssetsPickerController
10. CustomImagePicker
11. InstagramPhotoPicker
12. GMImagePicker
13. DLFPhotosPicker
14. CombinationPickerController
15. AssetPicker
16. BSImagePicker
17. SNImagePicker
18. DoImagePickerController
19. grabKit
20. IQMediaPickerController
21. HySideScrollingImagePicker
22. MultiImageSelector
23. TTImagePicker
24. SelectImages
25. ImageSelectAndSave
26. imagepicker-multi-select
27. MultiSelectImagePickerController
28. YangMingShan(Yahoo like image selector)
29. DBAttachmentPickerController
30. BRImagePicker
31. GLAssetGridViewController
32. CreolePhotoSelection
Swift
1. LimPicker (Similar to WhatsApp's image picker)
2. RMImagePicker
3. DKImagePickerController
4. BSImagePicker
5. Fusuma(Instagram like image selector)
6. YangMingShan(Yahoo like image selector)
7. NohanaImagePicker
8. ImagePicker
9. OpalImagePicker
10. TLPhotoPicker
11. AssetsPickerViewController
12. Alerts-and-pickers/Telegram Picker
Thanx to @androidbloke,
I have added some library that I know for multiple image picker in swift.
Will update list as I find new ones.
Thank You.
Changing the name of model name starting with Uppercase works. Example : Login_model.php instead of login_model.php
I hope the following code will help or solve your problem or you think not that understandable visit http://phppot.com/jquery/jquery-dependent-dropdown-list-countries-and-states/.
HTML DYNAMIC DEPENDENT SELECT
<div class="frmDronpDown">
<div class="row">
<label>Country:</label><br/>
<select name="country" id="country-list" class="demoInputBox" onChange="getState(this.value);">
<option value="">Select Country</option>
<?php
foreach($results as $country) {
?>
<option value="<?php echo $country["id"]; ?>"><?php echo $country["name"]; ?></option>
<?php
}
?>
</select>
</div>
<div class="row">
<label>State:</label><br/>
<select name="state" id="state-list" class="demoInputBox">
<option value="">Select State</option>
</select>
</div>
GETTING STATES VIA AJAX
<script> function getState(val) { $.ajax({
type: "POST",
url: "get_state.php",
data:'country_id='+val,
success: function(data){
$("#state-list").html(data);
}
});} </script>
READ STATE DATABASE USING PHP
<?php require_once("dbcontroller.php"); $db_handle = new DBController();if(!empty($_POST["country_id"])) {
$query ="SELECT * FROM states WHERE countryID = '" . $_POST["country_id"] . "'";
$results = $db_handle->runQuery($query); ?> <option value="">Select State</option><?php foreach($results as $state) { ?> <option value="<?php echo $state["id"]; ?>"><?php echo $state["name"]; ?></option><?php } } ?>
Take two numbers, lets say 9 and 10, write them as binary - 1001 and 1010.
Start with a result, R, of 0.
Take one of the numbers, 1010 in this case, we'll call it A, and shift it right by one bit, if you shift out a one, add the first number, we'll call it B, to R.
Now shift B left by one bit and repeat until all bits have been shifted out of A.
It's easier to see what's going on if you see it written out, this is the example:
0
0000 0
10010 1
000000 0
1001000 1
------
1011010
Updated: As of React > 0.16
Render method does not necessarily have to return a single element. An array can also be returned.
var indents = [];
for (var i = 0; i < this.props.level; i++) {
indents.push(<span className='indent' key={i}></span>);
}
return indents;
OR
return this.props.level.map((item, index) => (
<span className="indent" key={index}>
{index}
</span>
));
Docs here explaining about JSX children
OLD:
You can use one loop instead
var indents = [];
for (var i = 0; i < this.props.level; i++) {
indents.push(<span className='indent' key={i}></span>);
}
return (
<div>
{indents}
"Some text value"
</div>
);
You can also use .map and fancy es6
return (
<div>
{this.props.level.map((item, index) => (
<span className='indent' key={index} />
))}
"Some text value"
</div>
);
Also, you have to wrap the return value in a container. I used div in the above example
As the docs say here
Currently, in a component's render, you can only return one node; if you have, say, a list of divs to return, you must wrap your components within a div, span or any other component.
SELECT id, user_id, video_name
FROM sa_created_videos
ORDER BY LENGTH(id) ASC, LENGTH(user_id) DESC
I finally got it, submited it 13 times rejected for whatever reasons, 14th "the judge" accepted my answer, here it is :
import java.io.BufferedInputStream;
import java.util.Scanner;
public class HashmatWarrior {
public static void main(String args[]) {
Scanner stdin = new Scanner(new BufferedInputStream(System.in));
while (stdin.hasNext()) {
System.out.println(Math.abs(stdin.nextLong() - stdin.nextLong()));
}
}
}
To clean up some mess, trap
can be used. It can provide a list of stuff executed when a specific signal arrives:
trap "echo hello" SIGINT
but can also be used to execute something if the shell exits:
trap "killall background" EXIT
It's a builtin, so help trap
will give you information (works with bash). If you only want to kill background jobs, you can do
trap 'kill $(jobs -p)' EXIT
Watch out to use single '
, to prevent the shell from substituting the $()
immediately.
Nothing worked until I went this way: Settings>Developer options>Default USB configuration now you can choose your default USB connection purpose.
Yes, your compiler is expecting void *. Just cast them to void *.
/* for instance... */
printf("The value of s is: %p\n", (void *) s);
printf("The direction of s is: %p\n", (void *) &s);
Here is a working and simple solution for checking existence of a function and triggering that function dynamically by another function;
Trigger function
function runDynamicFunction(functionname){
if (typeof window[functionname] == "function") { //check availability
window[functionname]("this is from the function it"); // run function and pass a parameter to it
}
}
and you can now generate the function dynamically maybe using php like this
function runThis_func(my_Parameter){
alert(my_Parameter +" triggerd");
}
now you can call the function using dynamically generated event
<?php
$name_frm_somware ="runThis_func";
echo "<input type='button' value='Button' onclick='runDynamicFunction(\"".$name_frm_somware."\");'>";
?>
the exact HTML code you need is
<input type="button" value="Button" onclick="runDynamicFunction('runThis_func');">
The type char is a primitive -- not an object -- so it cannot be dereferenced
Dereferencing is the process of accessing the value referred to by a reference. Since a char is already a value (not a reference), it can not be dereferenced.
use Character
class:
if(Character.isLetter(c)) {
For an Ant project:
Make sure, you have servlet-api.jar in the lib folder.
For a Maven project:
Make sure, you have the dependency added in POM.xml.
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
Another way to do it is: Update the project facets to pick up the right server.
Check this box in this location:
Project ? Properties ? Target Runtimes ? Apache Tomcat (any server)
some thing as follows ::
Add this After the body tag
This is a rough sketch, you will need to modify it according to your needs.
<script>
var f = document.createElement("form");
f.setAttribute('method',"post");
f.setAttribute('action',"submit.php");
var i = document.createElement("input"); //input element, text
i.setAttribute('type',"text");
i.setAttribute('name',"username");
var s = document.createElement("input"); //input element, Submit button
s.setAttribute('type',"submit");
s.setAttribute('value',"Submit");
f.appendChild(i);
f.appendChild(s);
//and some more input elements here
//and dont forget to add a submit button
document.getElementsByTagName('body')[0].appendChild(f);
</script>
You should be able to access the document in the IFRAME using the following code:
document.getElementById('myframe').contentWindow.document
However, you will not be able to do this if the page in the frame is loaded from a different domain (such as google.com). THis is because of the browser's Same Origin Policy.
var seconds_inputs = document.getElementsByClassName('deal_left_seconds');_x000D_
var total_timers = seconds_inputs.length;_x000D_
for ( var i = 0; i < total_timers; i++){_x000D_
var str_seconds = 'seconds_'; var str_seconds_prod_id = 'seconds_prod_id_';_x000D_
var seconds_prod_id = seconds_inputs[i].getAttribute('data-value');_x000D_
var cal_seconds = seconds_inputs[i].getAttribute('value');_x000D_
_x000D_
eval('var ' + str_seconds + seconds_prod_id + '= ' + cal_seconds + ';');_x000D_
eval('var ' + str_seconds_prod_id + seconds_prod_id + '= ' + seconds_prod_id + ';');_x000D_
}_x000D_
function timer() {_x000D_
for ( var i = 0; i < total_timers; i++) {_x000D_
var seconds_prod_id = seconds_inputs[i].getAttribute('data-value');_x000D_
_x000D_
var days = Math.floor(eval('seconds_'+seconds_prod_id) / 24 / 60 / 60);_x000D_
var hoursLeft = Math.floor((eval('seconds_'+seconds_prod_id)) - (days * 86400));_x000D_
var hours = Math.floor(hoursLeft / 3600);_x000D_
var minutesLeft = Math.floor((hoursLeft) - (hours * 3600));_x000D_
var minutes = Math.floor(minutesLeft / 60);_x000D_
var remainingSeconds = eval('seconds_'+seconds_prod_id) % 60;_x000D_
_x000D_
function pad(n) {_x000D_
return (n < 10 ? "0" + n : n);_x000D_
}_x000D_
document.getElementById('deal_days_' + seconds_prod_id).innerHTML = pad(days);_x000D_
document.getElementById('deal_hrs_' + seconds_prod_id).innerHTML = pad(hours);_x000D_
document.getElementById('deal_min_' + seconds_prod_id).innerHTML = pad(minutes);_x000D_
document.getElementById('deal_sec_' + seconds_prod_id).innerHTML = pad(remainingSeconds);_x000D_
_x000D_
if (eval('seconds_'+ seconds_prod_id) == 0) {_x000D_
clearInterval(countdownTimer);_x000D_
document.getElementById('deal_days_' + seconds_prod_id).innerHTML = document.getElementById('deal_hrs_' + seconds_prod_id).innerHTML = document.getElementById('deal_min_' + seconds_prod_id).innerHTML = document.getElementById('deal_sec_' + seconds_prod_id).innerHTML = pad(0);_x000D_
} else {_x000D_
var value = eval('seconds_'+seconds_prod_id);_x000D_
value--;_x000D_
eval('seconds_' + seconds_prod_id + '= ' + value + ';');_x000D_
}_x000D_
}_x000D_
}_x000D_
_x000D_
var countdownTimer = setInterval('timer()', 1000);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<input type="hidden" class="deal_left_seconds" data-value="1" value="10">_x000D_
<div class="box-wrapper">_x000D_
<div class="date box"> <span class="key" id="deal_days_1">00</span> <span class="value">DAYS</span> </div>_x000D_
</div>_x000D_
<div class="box-wrapper">_x000D_
<div class="hour box"> <span class="key" id="deal_hrs_1">00</span> <span class="value">HRS</span> </div>_x000D_
</div>_x000D_
<div class="box-wrapper">_x000D_
<div class="minutes box"> <span class="key" id="deal_min_1">00</span> <span class="value">MINS</span> </div>_x000D_
</div>_x000D_
<div class="box-wrapper hidden-md">_x000D_
<div class="seconds box"> <span class="key" id="deal_sec_1">00</span> <span class="value">SEC</span> </div>_x000D_
</div>
_x000D_
Discord doesn't allow colored text. Though, currently, you have two options to "mimic" colored text.
Discord supports Markdown and uses highlight.js to highlight code-blocks.
Some programming languages have specific color outputs from highlight.js and can be used to mimic colored output.
To use code-blocks, send a normal message in this format (Which follows Markdown's standard format).
```language
message
```
Languages that currently reproduce nice colors: prolog (red/orange), css (yellow).
Discord now supports Embeds and Webhooks, which can be used to display colored blocks, they also support markdown. For documentation on how to use Embeds, please read your lib's documentation.
Using Autolayout
Add your scroll view inside a well defined view and then add the stack view inside the scroll view
Add top, left, right, bottom, center X and center Y constraints from scroll view and stack view to their relevant super views
Make sure that constraints are linked from stack view to the rightful superview (scrollview) since current default setting is to add an Align Top constraint and not a Top Space one.
I have a same problem, with volley, but this is my solution:
In Android Manifiest, in tag application add:
android:usesCleartextTraffic="true"
android:networkSecurityConfig="@xml/network_security_config"
create in folder xml this file network_security_config.xml and write this:
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<base-config cleartextTrafficPermitted="true" />
</network-security-config>
inside tag application add this tag:
<uses-library android:name="org.apache.http.legacy" android:required="false"/>
Have you tried using the concat() function?
ON tableTwo.query = concat('category_id=',tableOne.category_id)
In basic two way communication systems, socket.emit has proved to be more convincing and easy to use (personal experience) and is a part of Socket.IO which is primarily built for such purposes
I like Tony approach. It works, but I decided to implement in different way. Here my comments:
1) I did some tests and when using ng-style, Angular evaluates ng-style content, I mean getTableHeight() function more than once. I put a breakpoint into getTableHeight() function to analyze this.
By the way, ui-if was removed. Now you have ng-if build-in.
2) I prefer to write a service like this:
angular.module('angularStart.services').factory('uiGridService', function ($http, $rootScope) {
var factory = {};
factory.getGridHeight = function(gridOptions) {
var length = gridOptions.data.length;
var rowHeight = 30; // your row height
var headerHeight = 40; // your header height
var filterHeight = 40; // your filter height
return length * rowHeight + headerHeight + filterHeight + "px";
}
factory.removeUnit = function(value, unit) {
return value.replace(unit, '');
}
return factory;
});
And then in the controller write the following:
angular.module('app',['ui.grid']).controller('AppController', ['uiGridConstants', function(uiGridConstants) {
...
// Execute this when you have $scope.gridData loaded...
$scope.gridHeight = uiGridService.getGridHeight($scope.gridData);
And at the HTML file:
<div id="grid1" ui-grid="gridData" class="grid" ui-grid-auto-resize style="height: {{gridHeight}}"></div>
When angular applies the style, it only has to look in the $scope.gridHeight variable and not to evaluate a complete function.
3) If you want to calculate dynamically the height of an expandable grid, it is more complicated. In this case, you can set expandableRowHeight property. This fixes the reserved height for each subgrid.
$scope.gridData = {
enableSorting: true,
multiSelect: false,
enableRowSelection: true,
showFooter: false,
enableFiltering: true,
enableSelectAll: false,
enableRowHeaderSelection: false,
enableGridMenu: true,
noUnselect: true,
expandableRowTemplate: 'subGrid.html',
expandableRowHeight: 380, // 10 rows * 30px + 40px (header) + 40px (filters)
onRegisterApi: function(gridApi) {
gridApi.expandable.on.rowExpandedStateChanged($scope, function(row){
var height = parseInt(uiGridService.removeUnit($scope.jdeNewUserConflictsGridHeight,'px'));
var changedRowHeight = parseInt(uiGridService.getGridHeight(row.entity.subGridNewUserConflictsGrid, true));
if (row.isExpanded)
{
height += changedRowHeight;
}
else
{
height -= changedRowHeight;
}
$scope.jdeNewUserConflictsGridHeight = height + 'px';
});
},
columnDefs : [
{ field: 'GridField1', name: 'GridField1', enableFiltering: true }
]
}
Avoid the Date object creation w/ System.currentTimeMillis(). A divide by 1000 gets you to Unix epoch.
As mentioned in a comment, you typically want a primitive long (lower-case-l long) not a boxed object long (capital-L Long) for the unixTime variable's type.
long unixTime = System.currentTimeMillis() / 1000L;
Simple solution using itertools that preserves order (latter dicts have precedence)
# py2
from itertools import chain, imap
merge = lambda *args: dict(chain.from_iterable(imap(dict.iteritems, args)))
# py3
from itertools import chain
merge = lambda *args: dict(chain.from_iterable(map(dict.items, args)))
And it's usage:
>>> x = {'a':1, 'b': 2}
>>> y = {'b':10, 'c': 11}
>>> merge(x, y)
{'a': 1, 'b': 10, 'c': 11}
>>> z = {'c': 3, 'd': 4}
>>> merge(x, y, z)
{'a': 1, 'b': 10, 'c': 3, 'd': 4}
I just input some value that I knew was invalid and here is the output:
'whatToInput' is not a supported event for HtmlPanelGrid. Please specify one of these supported event names: click, dblclick, keydown, keypress, keyup, mousedown, mousemove, mouseout, mouseover, mouseup.
So values you can pass to event are
Answering your question directly: it does not require an internet connection, but access to a repository, on LAN or local disk (use hints from other people who posted here).
If your project is not in a mature phase, that means when POMs are changed quite often, offline mode will be very impractical, as you'll have to update your repository quite often, too. Unless you can get a copy of a repository that has everything you need, but how would you know? Usually you start a repository from scratch and it gets cloned gradually during development (on a computer connected to another repository). A copy of the repo1.maven.org public repository weighs hundreds of gigabytes, so I wouldn't recommend brute force, either.
Enter the image and give height:100%;width:auto
then just change the height of navbar itself to resize image. There is a really good example in codepen. https://codepen.io/bootstrapped/pen/KwYGwq
;(function($){
// your code
})(jQuery);
Place your js code inside the closure above , it should solve the problem.
You can find more information about which services it affects on the Microsoft docs.
Right click on "Command prompt" or "PowerShell", in menu click "Run as Administrator" (on Windows XP you can just run it as usual).
As Rick Vanover mentions in See what process is using a TCP port in Windows Server 2008
The following command will show what network traffic is in use at the port level:
Netstat -a -n -o
or
Netstat -a -n -o >%USERPROFILE%\ports.txt
(to open the port and process list in a text editor, where you can search for information you want)
Then,
with the PIDs listed in the netstat output, you can follow up with the Windows Task Manager (taskmgr.exe) or run a script with a specific PID that is using a port from the previous step. You can then use the "tasklist" command with the specific PID that corresponds to a port in question.
Example:
tasklist /svc /FI "PID eq 1348"
vector<T>::const_iterator first = myVec.begin() + 100000;
vector<T>::const_iterator last = myVec.begin() + 101000;
vector<T> newVec(first, last);
It's an O(N) operation to construct the new vector, but there isn't really a better way.
As mentioned by the top-voted answer, Martin Fowler discusses these distinctions in Mocks Aren't Stubs, and in particular the subheading The Difference Between Mocks and Stubs, so make sure to read that article.
Rather than focusing on how these things are different, I think it's more enlightening to focus on why these are distinct concepts. Each exists for a different purpose.
A fake is an implementation that behaves "naturally", but is not "real". These are fuzzy concepts and so different people have different understandings of what makes things a fake.
One example of a fake is an in-memory database (e.g. using sqlite with the :memory:
store). You would never use this for production (since the data is not persisted), but it's perfectly adequate as a database to use in a testing environment. It's also much more lightweight than a "real" database.
As another example, perhaps you use some kind of object store (e.g. Amazon S3) in production, but in a test you can simply save objects to files on disk; then your "save to disk" implementation would be a fake. (Or you could even fake the "save to disk" operation by using an in-memory filesystem instead.)
As a third example, imagine an object that provides a cache API; an object that implements the correct interface but that simply performs no caching at all but always returns a cache miss would be a kind of fake.
The purpose of a fake is not to affect the behavior of the system under test, but rather to simplify the implementation of the test (by removing unnecessary or heavyweight dependencies).
A stub is an implementation that behaves "unnaturally". It is preconfigured (usually by the test set-up) to respond to specific inputs with specific outputs.
The purpose of a stub is to get your system under test into a specific state. For example, if you are writing a test for some code that interacts with a REST API, you could stub out the REST API with an API that always returns a canned response, or that responds to an API request with a specific error. This way you could write tests that make assertions about how the system reacts to these states; for example, testing the response your users get if the API returns a 404 error.
A stub is usually implemented to only respond to the exact interactions you've told it to respond to. But the key feature that makes something a stub is its purpose: a stub is all about setting up your test case.
A mock is similar to a stub, but with verification added in. The purpose of a mock is to make assertions about how your system under test interacted with the dependency.
For example, if you are writing a test for a system that uploads files to a website, you could build a mock that accepts a file and that you can use to assert that the uploaded file was correct. Or, on a smaller scale, it's common to use a mock of an object to verify that the system under test calls specific methods of the mocked object.
Mocks are tied to interaction testing, which is a specific testing methodology. People who prefer to test system state rather than system interactions will use mocks sparingly if at all.
Fakes, stubs, and mocks all belong to the category of test doubles. A test double is any object or system you use in a test instead of something else. Most automated software testing involves the use of test doubles of some kind or another. Some other kinds of test doubles include dummy values, spies, and I/O blackholes.
You can also force flush the buffer to a file programmatically with the flush()
method.
with open('out.log', 'w+') as f:
f.write('output is ')
# some work
s = 'OK.'
f.write(s)
f.write('\n')
f.flush()
# some other work
f.write('done\n')
f.flush()
I have found this useful when tailing an output file with tail -f
.
OPTIONS
method returns info about API (methods/content type)
HEAD
method returns info about resource (version/length/type)
Server response
OPTIONS
HTTP/1.1 200 OK
Allow: GET,HEAD,POST,OPTIONS,TRACE
Content-Type: text/html; charset=UTF-8
Date: Wed, 08 May 2013 10:24:43 GMT
Content-Length: 0
HEAD
HTTP/1.1 200 OK
Accept-Ranges: bytes
Content-Type: text/html; charset=UTF-8
Date: Wed, 08 May 2013 10:12:29 GMT
ETag: "780602-4f6-4db31b2978ec0"
Last-Modified: Thu, 25 Apr 2013 16:13:23 GMT
Content-Length: 1270
OPTIONS
Identifying which HTTP methods a resource supports, e.g. can we DELETE it or update it via a PUT?HEAD
Checking whether a resource has changed. This is useful when maintaining a cached version of a resourceHEAD
Retrieving metadata about the resource, e.g. its media type or its size, before making a possibly costly retrievalHEAD, OPTIONS
Testing whether a resource exists and is accessible. For example, validating user-submitted links in an application
Here is nice and concise article about how HEAD and OPTIONS fit into RESTful architecture.
A simple example, where a change on a dropdown list triggers an ajax form-submit to reload a datagrid:
<div id="pnlSearch">
<% using (Ajax.BeginForm("UserSearch", "Home", new AjaxOptions { UpdateTargetId = "pnlSearchResults" }, new { id="UserSearchForm" }))
{ %>
UserType: <%: Html.DropDownList("FilterUserType", Model.UserTypes, "--", new { onchange = "$('#UserSearchForm').trigger('submit');" })%>
<% } %>
</div>
The trigger('onsubmit') is the key thing: it calls the onsubmit function that MVC has grafted onto the form.
NB. The UserSearchResults controller returns a PartialView that renders a table using the supplied Model
<div id="pnlSearchResults">
<% Html.RenderPartial("UserSearchResults", Model); %>
</div>
It is possible to print a 15 decimal number in C++ using the following:
#include <iomanip>
#include <iostream>
cout << fixed << setprecision(15) << " The Real_Pi is: " << real_pi << endl;
cout << fixed << setprecision(15) << " My Result_Pi is: " << my_pi << endl;
cout << fixed << setprecision(15) << " Processing error is: " << Error_of_Computing << endl;
cout << fixed << setprecision(15) << " Processing time is: " << End_Time-Start_Time << endl;
_getch();
return 0;
Try the following code:
start=$(date +'%s') && sleep 5 && echo "It took $(($(date +'%s') - $start)) seconds"
As mentioned here (in French), this can happen when you have two versions of R installed on your computer. Uninstall the oldest one, then try your package installation again! It worked fine for me.
import numpy as np
n = 51 #number of data points
# Suppose the real and imaginary parts are created independently
real_part = np.random.normal(size=n)
imag_part = np.random.normal(size=n)
# Create a complex array - the imaginary part will be equal to zero
z = np.array(real_part, dtype=complex)
# Now define the imaginary part:
z.imag = imag_part
print(z)
concurrent.futures.as_completed
https://docs.python.org/3.7/library/concurrent.futures.html#concurrent.futures.as_completed
The following solution:
Queue
Source:
#!/usr/bin/env python3
import concurrent.futures
import time
def func_that_raises(do_raise):
for i in range(3):
print(i)
time.sleep(0.1)
if do_raise:
raise Exception()
for i in range(3):
print(i)
time.sleep(0.1)
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor:
futures = []
futures.append(executor.submit(func_that_raises, False))
futures.append(executor.submit(func_that_raises, True))
for future in concurrent.futures.as_completed(futures):
print(repr(future.exception()))
Possible output:
0
0
1
1
2
2
0
Exception()
1
2
None
It is unfortunately not possible to kill futures to cancel the others as one fails:
concurrent.features
; Python: concurrent.futures How to make it cancelable?threading
: Is there any way to kill a Thread?If you do something like:
for future in concurrent.futures.as_completed(futures):
if future.exception() is not None:
raise future.exception()
then the with
catches it, and waits for the second thread to finish before continuing. The following behaves similarly:
for future in concurrent.futures.as_completed(futures):
future.result()
since future.result()
re-raises the exception if one occurred.
If you want to quit the entire Python process, you might get away with os._exit(0)
, but this likely means you need a refactor.
Custom class with perfect exception semantics
I ended up coding the perfect interface for myself at: The right way to limit maximum number of threads running at once? section "Queue example with error handling". That class aims to be both convenient, and give you total control over submission and result / error handling.
Tested on Python 3.6.7, Ubuntu 18.04.
try ToString method for your desirer format use
DateTime.Now.ToString("yyyy-MM-dd");
OR you can use it with your variable of DateTime type
dt.ToString("yyyy-MM-dd");
where dt is a DateTime variable
After checking the XHTML DTD I discovered that a <TD>-element is allowed to contain block elements like headings, lists and also <DIV>-elements. Thus, using a <DIV>-element inside a <TD>-element does not violate the XHTML standard. I'm pretty sure that other modern variations of HTML have an equivalent content model for the <TD>-element.
Here are the relevant DTD rules:
<!ELEMENT td %Flow;>
<!-- %Flow; mixes block and inline and is used for list items etc. -->
<!ENTITY %Flow "(#PCDATA | %block; | form | %inline; | %misc;>
<!ENTITY %block "p | %heading; | div | %lists; | %blocktext; | fieldset | table">
I was pretty sure that you need to specify the NOLOCK
for each JOIN
in the query. But my experience was limited to SQL Server 2005.
When I looked up MSDN just to confirm, I couldn't find anything definite. The below statements do seem to make me think, that for 2008, your two statements above are equivalent though for 2005 it is not the case:
[SQL Server 2008 R2]
All lock hints are propagated to all the tables and views that are accessed by the query plan, including tables and views referenced in a view. Also, SQL Server performs the corresponding lock consistency checks.
[SQL Server 2005]
In SQL Server 2005, all lock hints are propagated to all the tables and views that are referenced in a view. Also, SQL Server performs the corresponding lock consistency checks.
Additionally, point to note - and this applies to both 2005 and 2008:
The table hints are ignored if the table is not accessed by the query plan. This may be caused by the optimizer choosing not to access the table at all, or because an indexed view is accessed instead. In the latter case, accessing an indexed view can be prevented by using the
OPTION (EXPAND VIEWS)
query hint.
The easiest way of doing this is to convert both numbers to timestamps, then set these as the minimum and maximum bounds on a random number generator.
A quick PHP example would be:
// Find a randomDate between $start_date and $end_date
function randomDate($start_date, $end_date)
{
// Convert to timetamps
$min = strtotime($start_date);
$max = strtotime($end_date);
// Generate random number using above bounds
$val = rand($min, $max);
// Convert back to desired date format
return date('Y-m-d H:i:s', $val);
}
This function makes use of strtotime()
to convert a datetime description into a Unix timestamp, and date()
to make a valid date out of the random timestamp which has been generated.
That's because abc
is undefined at the moment of the template rendering. You can use safe navigation operator (?
) to "protect" template until HTTP call is completed:
{{abc?.xyz?.name}}
You can read more about safe navigation operator here.
Update:
Safe navigation operator can't be used in arrays, you will have to take advantage of NgIf
directive to overcome this problem:
<div *ngIf="arr && arr.length > 0">
{{arr[0].name}}
</div>
Read more about NgIf
directive here.
To manipulate the white space, use str_trim() in the stringr package. The package has manual dated Feb 15, 2013 and is in CRAN. The function can also handle string vectors.
install.packages("stringr", dependencies=TRUE)
require(stringr)
example(str_trim)
d4$clean2<-str_trim(d4$V2)
(Credit goes to commenter: R. Cotton)
Card view can't show shadow because of your RelativeLayout
is on the card view's shadow. To show the shadow add margins on your Card view. For example:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginTop="4dp"
android:layout_marginBottom="8dp">
</android.support.v7.widget.CardView>
</RelativeLayout>
The animate(..)
function' signature is:
.animate( properties, options );
And it says the following about the parameter properties
:
properties A map of CSS properties that the animation will move toward.
text
is not a CSS property, this is why the function isn't working as you expected.
Do you want to fade the text out? Do you want to move it? I might be able to provide an alternative.
Have a look at the following fiddle.
I have a clearer proposal on automatic search in a DataGridView
this is an example
private void searchTb_TextChanged(object sender, EventArgs e)
{
try
{
(lecteurdgview.DataSource as DataTable).DefaultView.RowFilter = String.IsNullOrEmpty(searchTb.Text) ?
"lename IS NOT NULL" :
String.Format("lename LIKE '{0}' OR lecni LIKE '{1}' OR ledatenais LIKE '{2}' OR lelieu LIKE '{3}'", searchTb.Text, searchTb.Text, searchTb.Text, searchTb.Text);
}
catch (Exception ex) {
MessageBox.Show(ex.StackTrace);
}
}
The FileNameExtensionFilter
class is intended for Swing to be used in a JFileChooser
.
Try using a FilenameFilter
instead. For example:
File dir = new File("/users/blah/dirname");
File[] files = dir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(".txt");
}
});
While Esq's answer works, I've added my own implementation which is more in line with good component architecture by separating the view into it's own class. It also uses dynamic blurring introduced in iOS 8.
Here is how mine looks with an image background:
The code for this is encapsulated in it's own UIView class which means you can reuse it whenever you desire.
Usage
func viewDidLoad() {
super.viewDidLoad()
// Create and add the view to the screen.
let progressHUD = ProgressHUD(text: "Saving Photo")
self.view.addSubview(progressHUD)
// All done!
self.view.backgroundColor = UIColor.black
}
UIView Code
import UIKit
class ProgressHUD: UIVisualEffectView {
var text: String? {
didSet {
label.text = text
}
}
let activityIndictor: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.gray)
let label: UILabel = UILabel()
let blurEffect = UIBlurEffect(style: .light)
let vibrancyView: UIVisualEffectView
init(text: String) {
self.text = text
self.vibrancyView = UIVisualEffectView(effect: UIVibrancyEffect(blurEffect: blurEffect))
super.init(effect: blurEffect)
self.setup()
}
required init?(coder aDecoder: NSCoder) {
self.text = ""
self.vibrancyView = UIVisualEffectView(effect: UIVibrancyEffect(blurEffect: blurEffect))
super.init(coder: aDecoder)
self.setup()
}
func setup() {
contentView.addSubview(vibrancyView)
contentView.addSubview(activityIndictor)
contentView.addSubview(label)
activityIndictor.startAnimating()
}
override func didMoveToSuperview() {
super.didMoveToSuperview()
if let superview = self.superview {
let width = superview.frame.size.width / 2.3
let height: CGFloat = 50.0
self.frame = CGRect(x: superview.frame.size.width / 2 - width / 2,
y: superview.frame.height / 2 - height / 2,
width: width,
height: height)
vibrancyView.frame = self.bounds
let activityIndicatorSize: CGFloat = 40
activityIndictor.frame = CGRect(x: 5,
y: height / 2 - activityIndicatorSize / 2,
width: activityIndicatorSize,
height: activityIndicatorSize)
layer.cornerRadius = 8.0
layer.masksToBounds = true
label.text = text
label.textAlignment = NSTextAlignment.center
label.frame = CGRect(x: activityIndicatorSize + 5,
y: 0,
width: width - activityIndicatorSize - 15,
height: height)
label.textColor = UIColor.gray
label.font = UIFont.boldSystemFont(ofSize: 16)
}
}
func show() {
self.isHidden = false
}
func hide() {
self.isHidden = true
}
}
An example on how to use it is like this:
override func viewDidLoad() {
super.viewDidLoad()
// Create and add the view to the screen.
let progressHUD = ProgressHUD(text: "Saving Photo")
self.view.addSubview(progressHUD)
// All done!
self.view.backgroundColor = UIColor.blackColor()
}
Here is the UIView code:
import UIKit
class ProgressHUD: UIVisualEffectView {
var text: String? {
didSet {
label.text = text
}
}
let activityIndictor: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.White)
let label: UILabel = UILabel()
let blurEffect = UIBlurEffect(style: .Light)
let vibrancyView: UIVisualEffectView
init(text: String) {
self.text = text
self.vibrancyView = UIVisualEffectView(effect: UIVibrancyEffect(forBlurEffect: blurEffect))
super.init(effect: blurEffect)
self.setup()
}
required init(coder aDecoder: NSCoder) {
self.text = ""
self.vibrancyView = UIVisualEffectView(effect: UIVibrancyEffect(forBlurEffect: blurEffect))
super.init(coder: aDecoder)
self.setup()
}
func setup() {
contentView.addSubview(vibrancyView)
vibrancyView.contentView.addSubview(activityIndictor)
vibrancyView.contentView.addSubview(label)
activityIndictor.startAnimating()
}
override func didMoveToSuperview() {
super.didMoveToSuperview()
if let superview = self.superview {
let width = superview.frame.size.width / 2.3
let height: CGFloat = 50.0
self.frame = CGRectMake(superview.frame.size.width / 2 - width / 2,
superview.frame.height / 2 - height / 2,
width,
height)
vibrancyView.frame = self.bounds
let activityIndicatorSize: CGFloat = 40
activityIndictor.frame = CGRectMake(5, height / 2 - activityIndicatorSize / 2,
activityIndicatorSize,
activityIndicatorSize)
layer.cornerRadius = 8.0
layer.masksToBounds = true
label.text = text
label.textAlignment = NSTextAlignment.Center
label.frame = CGRectMake(activityIndicatorSize + 5, 0, width - activityIndicatorSize - 15, height)
label.textColor = UIColor.grayColor()
label.font = UIFont.boldSystemFontOfSize(16)
}
}
func show() {
self.hidden = false
}
func hide() {
self.hidden = true
}
}
I hope this helps, please feel free to use this code wherever you need.
You can layer gradient shapes in the xml using a layer-list. Imagine a button with the default state as below, where the second item is semi-transparent. It adds a sort of vignetting. (Please excuse the custom-defined colours.)
<!-- Normal state. -->
<item>
<layer-list>
<item>
<shape>
<gradient
android:startColor="@color/grey_light"
android:endColor="@color/grey_dark"
android:type="linear"
android:angle="270"
android:centerColor="@color/grey_mediumtodark" />
<stroke
android:width="1dp"
android:color="@color/grey_dark" />
<corners
android:radius="5dp" />
</shape>
</item>
<item>
<shape>
<gradient
android:startColor="#00666666"
android:endColor="#77666666"
android:type="radial"
android:gradientRadius="200"
android:centerColor="#00666666"
android:centerX="0.5"
android:centerY="0" />
<stroke
android:width="1dp"
android:color="@color/grey_dark" />
<corners
android:radius="5dp" />
</shape>
</item>
</layer-list>
</item>
This is a question with a simple answer and a long-winded answer.
The simple answer is the heap. Classes and all of the data applying to classes (not instance data) is stored in the Permanent Generation section of the heap.
The long answer is already on stack overflow:
There is a thorough description of memory and garbage collection in the JVM as well as an answer that talks more concisely about it.
Do it in 2 steps. First, create a dictionary.
>>> input = [('11013331', 'KAT'), ('9085267', 'NOT'), ('5238761', 'ETH'), ('5349618', 'ETH'), ('11788544', 'NOT'), ('962142', 'ETH'), ('7795297', 'ETH'), ('7341464', 'ETH'), ('9843236', 'KAT'), ('5594916', 'ETH'), ('1550003', 'ETH')]
>>> from collections import defaultdict
>>> res = defaultdict(list)
>>> for v, k in input: res[k].append(v)
...
Then, convert that dictionary into the expected format.
>>> [{'type':k, 'items':v} for k,v in res.items()]
[{'items': ['9085267', '11788544'], 'type': 'NOT'}, {'items': ['5238761', '5349618', '962142', '7795297', '7341464', '5594916', '1550003'], 'type': 'ETH'}, {'items': ['11013331', '9843236'], 'type': 'KAT'}]
It is also possible with itertools.groupby but it requires the input to be sorted first.
>>> sorted_input = sorted(input, key=itemgetter(1))
>>> groups = groupby(sorted_input, key=itemgetter(1))
>>> [{'type':k, 'items':[x[0] for x in v]} for k, v in groups]
[{'items': ['5238761', '5349618', '962142', '7795297', '7341464', '5594916', '1550003'], 'type': 'ETH'}, {'items': ['11013331', '9843236'], 'type': 'KAT'}, {'items': ['9085267', '11788544'], 'type': 'NOT'}]
Note both of these do not respect the original order of the keys. You need an OrderedDict if you need to keep the order.
>>> from collections import OrderedDict
>>> res = OrderedDict()
>>> for v, k in input:
... if k in res: res[k].append(v)
... else: res[k] = [v]
...
>>> [{'type':k, 'items':v} for k,v in res.items()]
[{'items': ['11013331', '9843236'], 'type': 'KAT'}, {'items': ['9085267', '11788544'], 'type': 'NOT'}, {'items': ['5238761', '5349618', '962142', '7795297', '7341464', '5594916', '1550003'], 'type': 'ETH'}]
You may get this error when trying to browse an ASP.NET application.
The debug information shows that "This error can be caused by a virtual directory not being configured as an application in IIS."
However, this error occurs primarily out of two scenarios.
To resolve it, right click on the virtual directory - select properties and then click on "Create" next to the "Application" Label and the text box. It will automatically create the "application" using the virtual directory's name. Now the application can be accessed.
web.config
of the sub-directory such as authentication, session state (you may see that the error message shows the line number where the authentication or session state is declared in the web.config of the sub-directory). The reason is, these settings cannot be overridden at the sub-directory level unless the sub-directory is also configured as an application (as mentioned in the above point). Mostly, we have the practice of adding web.config
in the sub-directory if we want to protect access to the sub-directory files (say, the directory is admin and we wish to protect the admin pages from unauthorized users).
From Get-ScriptDirectory to the Rescue blog entry ...
function Get-ScriptDirectory
{
$Invocation = (Get-Variable MyInvocation -Scope 1).Value
Split-Path $Invocation.MyCommand.Path
}
I think your problem is when displaying the decimal, not the contents of it.
If you try
string value = "1200.00";
decimal d = decimal.Parse(s);
string s = d.ToString();
s
will contain the string "1200"
.
However if you change your code to this
string value = "1200.00";
decimal d = decimal.Parse(s);
string s = d.ToString("0.00");
s
will contain the string "1200.00"
as you want it to do.
EDIT
Seems I'm braindead early in the morning today. I added the Parse
statements now. However even my first code will output "1200.00", even if I expected it to output "1200". Seems like I'm learning something each day, and in this case obviously something that is quite basic.
So disregard this a an proper answer. We will probably need more code to identify your problem in this case.
Assuming popup
is the ID of your "description box":
HTML
<div id="parent"> <!-- This is the main container, to mouse over -->
<div id="popup" style="display: none">description text here</div>
</div>
JavaScript
var e = document.getElementById('parent');
e.onmouseover = function() {
document.getElementById('popup').style.display = 'block';
}
e.onmouseout = function() {
document.getElementById('popup').style.display = 'none';
}
Alternatively you can get rid of JavaScript entirely and do it just with CSS:
CSS
#parent #popup {
display: none;
}
#parent:hover #popup {
display: block;
}
If you're inserting text content in your document in a location where text content is expected1, you typically only need to escape the same characters as you would in XML. Inside of an element, this just includes the entity escape ampersand &
and the element delimiter less-than and greater-than signs <
>
:
& becomes &
< becomes <
> becomes >
Inside of attribute values you must also escape the quote character you're using:
" becomes "
' becomes '
In some cases it may be safe to skip escaping some of these characters, but I encourage you to escape all five in all cases to reduce the chance of making a mistake.
If your document encoding does not support all of the characters that you're using, such as if you're trying to use emoji in an ASCII-encoded document, you also need to escape those. Most documents these days are encoded using the fully Unicode-supporting UTF-8 encoding where this won't be necessary.
In general, you should not escape spaces as
.
is not a normal space, it's a non-breaking space. You can use these instead of normal spaces to prevent a line break from being inserted between two words, or to insert extra space without it being automatically collapsed, but this is usually a rare case. Don't do this unless you have a design constraint that requires it.
1 By "a location where text content is expected", I mean inside of an element or quoted attribute value where normal parsing rules apply. For example: <p>HERE</p>
or <p title="HERE">...</p>
. What I wrote above does not apply to content that has special parsing rules or meaning, such as inside of a script or style tag, or as an element or attribute name. For example: <NOT-HERE>...</NOT-HERE>
, <script>NOT-HERE</script>
, <style>NOT-HERE</style>
, or <p NOT-HERE="...">...</p>
.
In these contexts, the rules are more complicated and it's much easier to introduce a security vulnerability. I strongly discourage you from ever inserting dynamic content in any of these locations. I have seen teams of competent security-aware developers introduce vulnerabilities by assuming that they had encoded these values correctly, but missing an edge case. There's usually a safer alternative, such as putting the dynamic value in an attribute and then handling it with JavaScript.
If you must, please read the Open Web Application Security Project's XSS Prevention Rules to help understand some of the concerns you will need to keep in mind.
Building on Mike Monkiewicz answer you can also specify a single or more files to checkout from the supplied sha1/branch.
git checkout -p bc66559 -- path/to/file.java
This will allow you to interactively pick the changes you want to have applied to your current version of the file.
in function
def handleUpload():
if 'photo' in request.files:
photo = request.files['photo']
if photo.filename != '':
image = request.files['photo']
image_string = base64.b64encode(image.read())
image_string = image_string.decode('utf-8')
#use this to remove b'...' to get raw string
return render_template('handleUpload.html',filestring = image_string)
return render_template('upload.html')
in html file
<html>
<head>
<title>Simple file upload using Python Flask</title>
</head>
<body>
{% if filestring %}
<h1>Raw image:</h1>
<h1>{{filestring}}</h1>
<img src="data:image/png;base64, {{filestring}}" alt="alternate" />.
{% else %}
<h1></h1>
{% endif %}
</body>
I was getting the exact same errors. I battled this issue for a few hours today. It seemed to be caused by a mismatch between the versions of chromedriver and selenium-server-standalone. The config.js file was referencing a directory that had chromedriver 2.9 and selenium-server-standalone 2.35.0. Once I made sure we were referencing 2.10 and 2.42.2, it worked.
.py
: This is normally the input source code that you've written..pyc
: This is the compiled bytecode. If you import a module, python will build a *.pyc
file that contains the bytecode to make importing it again later easier (and faster)..pyo
: This was a file format used before Python 3.5 for *.pyc
files that were created with optimizations (-O
) flag. (see the note below).pyd
: This is basically a windows dll file. http://docs.python.org/faq/windows.html#is-a-pyd-file-the-same-as-a-dllAlso for some further discussion on .pyc
vs .pyo
, take a look at: http://www.network-theory.co.uk/docs/pytut/CompiledPythonfiles.html (I've copied the important part below)
- When the Python interpreter is invoked with the -O flag, optimized code is generated and stored in ‘.pyo’ files. The optimizer currently doesn't help much; it only removes assert statements. When -O is used, all bytecode is optimized; .pyc files are ignored and .py files are compiled to optimized bytecode.
- Passing two -O flags to the Python interpreter (-OO) will cause the bytecode compiler to perform optimizations that could in some rare cases result in malfunctioning programs. Currently only
__doc__
strings are removed from the bytecode, resulting in more compact ‘.pyo’ files. Since some programs may rely on having these available, you should only use this option if you know what you're doing.- A program doesn't run any faster when it is read from a ‘.pyc’ or ‘.pyo’ file than when it is read from a ‘.py’ file; the only thing that's faster about ‘.pyc’ or ‘.pyo’ files is the speed with which they are loaded.
- When a script is run by giving its name on the command line, the bytecode for the script is never written to a ‘.pyc’ or ‘.pyo’ file. Thus, the startup time of a script may be reduced by moving most of its code to a module and having a small bootstrap script that imports that module. It is also possible to name a ‘.pyc’ or ‘.pyo’ file directly on the command line.
Note:
On 2015-09-15 the Python 3.5 release implemented PEP-488 and eliminated .pyo
files.
This means that .pyc
files represent both unoptimized and optimized bytecode.
You can get the icons from the android sdk they are in this folder
$android-sdk\platforms\android-xx\data\res
Check out this library: https://github.com/robfig/cron
Example as below:
c := cron.New()
c.AddFunc("0 30 * * * *", func() { fmt.Println("Every hour on the half hour") })
c.AddFunc("@hourly", func() { fmt.Println("Every hour") })
c.AddFunc("@every 1h30m", func() { fmt.Println("Every hour thirty") })
c.Start()
Windows 10 appears to have a keyboard shortcut. According to How to open elevated command prompt in Windows 10 you can press ctrl + shift + enter from the search or start menu after typing cmd
for the search term.
(source: winaero.com)
your xpath should work . i have tested your xpath and mine in both MarkLogic and Zorba Xquery/ Xpath implementation.
Both should work.
/node/child::text()[1] - should return Text1
/node/child::text()[2] - should return text2
/node/text()[1] - should return Text1
/node/text()[2] - should return text2
t(sapply(a, '[', 1:max(sapply(a, length))))
where 'a' is a list. Would work for unequal row size
In my case, I created a folder audio
in res
directory. That caused the problem! Deleting the folder fixed it. Hope it might help someone.
An alternative option I like to use with MSSQL Server Deveploper or Enterprise is to create a snapshot of the database immediately after creating the empty schema. At that point you can just keep restoring the database back to the snapshot.
Here's an iterator-based method.
ifstream file("file", ios::binary);
string fileStr;
istreambuf_iterator<char> inputIt(file), emptyInputIt
back_insert_iterator<string> stringInsert(fileStr);
copy(inputIt, emptyInputIt, stringInsert);
There are some really good answers and attempts to answer your question here. I am not an encoding master, but I understand your desire to have a pure UTF-8 stack all the way through to your database. I have been using MySQL's utf8mb4
encoding for tables, fields, and connections.
My situation boiled down to "I just want my sanitizers, validators, business logic, and prepared statements to deal with UTF-8 when data comes from HTML forms, or e-mail registration links." So, in my simple way, I started off with this idea:
$encodings = ['UTF-8', 'ISO-8859-1', 'ASCII'];
throw new RuntimeException
UTF-8
, carry on.Else, if it is ISO-8859-1
or ASCII
a. Attempt conversion to UTF-8 (wait, not finished)
b. Detect the encoding of the converted value
c. If the reported encoding and converted value are both UTF-8
, carry on.
d. Else, throw new RuntimeException
From my abstract class Sanitizer
private function isUTF8($encoding, $value)
{
return (($encoding === 'UTF-8') && (utf8_encode(utf8_decode($value)) === $value));
}
private function utf8tify(&$value)
{
$encodings = ['UTF-8', 'ISO-8859-1', 'ASCII'];
mb_internal_encoding('UTF-8');
mb_substitute_character(0xfffd); //REPLACEMENT CHARACTER
mb_detect_order($encodings);
$stringEncoding = mb_detect_encoding($value, $encodings, true);
if (!$stringEncoding) {
$value = null;
throw new \RuntimeException("Unable to identify character encoding in sanitizer.");
}
if ($this->isUTF8($stringEncoding, $value)) {
return;
} else {
$value = mb_convert_encoding($value, 'UTF-8', $stringEncoding);
$stringEncoding = mb_detect_encoding($value, $encodings, true);
if ($this->isUTF8($stringEncoding, $value)) {
return;
} else {
$value = null;
throw new \RuntimeException("Unable to convert character encoding from ISO-8859-1, or ASCII, to UTF-8 in Sanitizer.");
}
}
return;
}
One could make an argument that I should separate encoding concerns from my abstract Sanitizer
class and simply inject an Encoder
object into a concrete child instance of Sanitizer
. However, the main problem with my approach is that, without more knowledge, I simply reject encoding types that I do not want (and I am relying on PHP mb_* functions). Without further study, I cannot know if that hurts some populations or not (or, if I am losing out on important information). So, I need to learn more. I found this article.
Moreover, what happens when encrypted data is added to my email registration links (using OpenSSL
or mcrypt
)? Could this interfere with decoding? What about Windows-1252? What about security implications? The use of utf8_decode()
and utf8_encode()
in Sanitizer::isUTF8
are dubious.
People have pointed out short-comings in the PHP mb_* functions. I never took time to investigate iconv
, but if it works better than mb_*functions, let me know.
Escaping quotes in VB6 or VBScript strings is simple in theory although often frightening when viewed. You escape a double quote with another double quote.
An example:
"c:\program files\my app\app.exe"
If I want to escape the double quotes so I could pass this to the shell execute function listed by Joe or the VB6 Shell function I would write it:
escapedString = """c:\program files\my app\app.exe"""
How does this work? The first and last quotes wrap the string and let VB know this is a string. Then each quote that is displayed literally in the string has another double quote added in front of it to escape it.
It gets crazier when you are trying to pass a string with multiple quoted sections. Remember, every quote you want to pass has to be escaped.
If I want to pass these two quoted phrases as a single string separated by a space (which is not uncommon):
"c:\program files\my app\app.exe" "c:\documents and settings\steve"
I would enter this:
escapedQuoteHell = """c:\program files\my app\app.exe"" ""c:\documents and settings\steve"""
I've helped my sysadmins with some VBScripts that have had even more quotes.
It's not pretty, but that's how it works.
import java.util.Scanner;
import java.io.*;
then
try {
Scanner input = new Scanner(new File("lettered.in"));
int dataCollect = input.nextInt();
int sum = 0;
String lineInput = "";
for (int i = 0; i <= dataCollect; i++) {
while (input.hasNext()) {
lineInput = input.next();
char lineArray[] = lineInput.toCharArray();
for (int j = 0; j < lineArray.length; j++) {
switch(lineArray[j]) {
case 'A': {
sum += 1;
continue;
}
case 'B': {
sum += 10;
continue;
}
case 'C': {
sum += 100;
}
case 'D': {
sum += 1000;
continue;
}
case 'E': {
sum += 10000;
continue;
}
case 'F': {
sum += 100000;
continue;
}
case: 'G': {
sum += 1000000;
continue;
}
case 'X': {
System.out.println(sum);
sum = 0;
continue;
}
default: {}
}
}
}
}
} catch (FileNotFoundException fileNotFound) {
System.out.println("File has not been found.");
}
I just ran into this... my gif didn't run on the server that I was testing on, but when I published the code it ran on my desktop just fine...
In advance of my questions being answered, this is how I'd go about it:
Minimize the number of statements and the work they do issued in relative terms.
All scenarios assume you have a table of IDs (PURGE_IDS
) to delete from TABLE_1
, TABLE_2
, etc.
Consider Using CREATE TABLE AS SELECT for really large deletes
If there's no concurrent activity, and you're deleting 30+ % of the rows in one or more of the tables, don't delete; perform a create table as select
with the rows you wish to keep, and swap the new table out for the old table. INSERT /*+ APPEND */ ... NOLOGGING
is surprisingly cheap if you can afford it. Even if you do have some concurrent activity, you may be able to use Online Table Redefinition to rebuild the table in-place.
Don't run DELETE statements you know won't delete any rows
If an ID value exists in at most one of the six tables, then keep track of which IDs you've deleted - and don't try to delete those IDs from any of the other tables.
CREATE TABLE TABLE1_PURGE NOLOGGING
AS
SELECT ID FROM PURGE_IDS INNER JOIN TABLE_1 ON PURGE_IDS.ID = TABLE_1.ID;
DELETE FROM TABLE1 WHERE ID IN (SELECT ID FROM TABLE1_PURGE);
DELETE FROM PURGE_IDS WHERE ID IN (SELECT ID FROM TABLE1_PURGE);
DROP TABLE TABLE1_PURGE;
and repeat.
Manage Concurrency if you have to
Another way is to use PL/SQL looping over the tables, issuing a rowcount-limited delete statement. This is most likely appropriate if there's significant insert/update/delete concurrent load against the tables you're running the deletes against.
declare
l_sql varchar2(4000);
begin
for i in (select table_name from all_tables
where table_name in ('TABLE_1', 'TABLE_2', ...)
order by table_name);
loop
l_sql := 'delete from ' || i.table_name ||
' where id in (select id from purge_ids) ' ||
' and rownum <= 1000000';
loop
commit;
execute immediate l_sql;
exit when sql%rowcount <> 1000000; -- if we delete less than 1,000,000
end loop; -- no more rows need to be deleted!
end loop;
commit;
end;
I had quite a number of these exceptions thrown, the fastest and easiest way I found to solve them was to find unique values in the exceptions which I then searched for in the storyboard source code. This helped me to find the actual view(s) and constraint(s) causing the problem (I use meaningful userLabels on all of the views, which makes it a lot easier to track the constraints and views)...
So, using the above exceptions I would open the storyboard as "source code" in xcode (or another editor) and look for something I can find...
<NSLayoutConstraint:0x72bf860 V:[UILabel:0x72bf7c0(17)]>
.. this looks like a vertical (V) constraint on a UILabel with a value of (17).
Looking through the exceptions I also find
<NSLayoutConstraint:0x72c22b0 V:[UILabel:0x72bf7c0]-(NSSpace(8))-[UIButton:0x886efe0]>
Which looks like the UILabel(0x72bf7c0) is close to a UIButton(0x886efe0) with some vertical spacing (8)..
That will hopefully be enough for me to find the specific views in the storyboard source code (probably by searching the text for "17" initially), or at least a few likely candidates. From there I should be able to actually figure out which views these are in the storyboard which will make it a lot easier to identify the problem (look for "duplicated" pinning or pinning that conflicts with size constraints).
The default value for a GUID is empty. (eg: 00000000-0000-0000-0000-000000000000)
This can be invoked using Guid.Empty
or new Guid()
If you want a new GUID, you use Guid.NewGuid()
Just call fig.tight_layout()
as you normally would. (pyplot
is just a convenience wrapper. In most cases, you only use it to quickly generate figure and axes objects and then call their methods directly.)
There shouldn't be a difference between the QtAgg
backend and the default backend (or if there is, it's a bug).
E.g.
import matplotlib.pyplot as plt
#-- In your case, you'd do something more like:
# from matplotlib.figure import Figure
# fig = Figure()
#-- ...but we want to use it interactive for a quick example, so
#-- we'll do it this way
fig, axes = plt.subplots(nrows=4, ncols=4)
for i, ax in enumerate(axes.flat, start=1):
ax.set_title('Test Axes {}'.format(i))
ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
plt.show()
import matplotlib.pyplot as plt
fig, axes = plt.subplots(nrows=4, ncols=4)
for i, ax in enumerate(axes.flat, start=1):
ax.set_title('Test Axes {}'.format(i))
ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
fig.tight_layout()
plt.show()
Since Java 8 you can sort using the Streams API:
List<String> fruits = Arrays.asList("apple", "Apricot", "banana");
List<String> sortedFruit = fruits.stream()
.sorted(String.CASE_INSENSITIVE_ORDER)
.collect(Collectors.toList())
The difference with Collections.sort
is that this will return a new list and will not modify the existing one.
Maybe not the most efficient way. But you could convert the list into a vector.
#include <list>
#include <vector>
list<Object> myList;
vector<Object> myVector(myList.begin(), myList.end());
Then access the vector using the [x] operator.
auto x = MyVector[0];
You could put that in a helper function:
#include <memory>
#include <vector>
#include <list>
template<class T>
shared_ptr<vector<T>>
ListToVector(list<T> List) {
shared_ptr<vector<T>> Vector {
new vector<string>(List.begin(), List.end()) }
return Vector;
}
Then use the helper funciton like this:
auto MyVector = ListToVector(Object);
auto x = MyVector[0];
Web developement generally involves html pages that hold forms (<form>
tags). Forms post to URLs. You can set a given form to post to any url you want to. A postback is when a form posts back to it's own page/url.
The term has special significance for ASP.Net developers, because it is the primary mechanism that drives a lot of the behavior for a page -- specifically 'event handling'. ASP.Net pages have exactly one server form that nearly always posts back to itself, and these post backs trigger execution on the server of something called the Page Lifecycle.
One 'elegant' solution would be to use full text search: http://www.postgresql.org/docs/9.0/interactive/textsearch.html. Then you would use full text search queries.
The code says everything:
max@serv$ chmod 777 .
Okay, it doesn't say everything.
In UNIX and Linux, the ability to remove a file is not determined by the access bits of that file. It is determined by the access bits of the directory which contains the file.
Think of it this way -- deleting a file doesn't modify that file. You aren't writing to the file, so why should "w" on the file matter? Deleting a file requires editing the directory that points to the file, so you need "w" on the that directory.
I moved a database mdf from the default Data folder to my asp.net app_data folder and ran into this problem trying to set the database back online.
I compared the security settings of the other file databases in the original location to the moved files and noticed that MSSQL$SQLEXPRESS was not assigned permissions to the files in their new location. I added Full control for "NT SERVICE\MSSQL$SQLEXPRESS" (must include that NT SERVICE) and it attached just fine.
It appears that the original Data folder has these permissions and the files inherit it. Move the files and the inheritance breaks of course.
I checked another project's mdf file which I created directly into its app_data folder. it does not have MSSQL$SQLEXPRESS permissions. Hmmm. I wonder why SQL Express likes one but not the other?
As has already been suggested, Flexbox is the answer - particularly because you only need to support a single modern browser: Mobile Safari.
See: http://jsfiddle.net/thirtydot/hLUHL/
You can remove the -moz-
prefixed properties if you like, I just left them in for future readers.
#blockContainer {_x000D_
display: -webkit-box;_x000D_
display: -moz-box;_x000D_
display: box;_x000D_
_x000D_
-webkit-box-orient: vertical;_x000D_
-moz-box-orient: vertical;_x000D_
box-orient: vertical;_x000D_
}_x000D_
#blockA {_x000D_
-webkit-box-ordinal-group: 2;_x000D_
-moz-box-ordinal-group: 2;_x000D_
box-ordinal-group: 2;_x000D_
}_x000D_
#blockB {_x000D_
-webkit-box-ordinal-group: 3;_x000D_
-moz-box-ordinal-group: 3;_x000D_
box-ordinal-group: 3;_x000D_
}
_x000D_
<div id="blockContainer">_x000D_
<div id="blockA">Block A</div>_x000D_
<div id="blockB">Block B</div>_x000D_
<div id="blockC">Block C</div>_x000D_
</div>
_x000D_
I just had the same problem and discovered an alternative solution using the validation API - works without black magic in all major browsers (Chrome, Firefox, Safari) except IE. This solution simply prevents users from entering invalid values. I also included a fallback for IE, which is not nice but works at least.
Context: onInput function is called on input events, setInputValue is used to set the value of the input element, previousInputValue contains the last valid input value (updated in setInputValue calls).
function onInput (event) {
const inputValue = event.target.value;
// badInput supported on validation api (except IE)
// in IE it will be undefined, so we need strict value check
const badInput = event.target.validity.badInput;
// simply prevent modifying the value
if (badInput === true) {
// it's still possible to enter invalid values in an empty input, so we'll need this trick to prevent that
if (previousInputValue === '') {
setInputValue(' ');
setTimeout(() => {
setInputValue('');
}, 1);
}
return;
}
if (badInput === false) {
setInputValue(inputValue);
return;
}
// fallback case for IE and other abominations
// remove everything from the string expect numbers, point and comma
// replace comma with points (parseFloat works only with points)
let stringVal = String(inputValue)
.replace(/([^0-9.,])/g, '')
.replace(/,/g, '.');
// remove all but first point
const pointIndex = stringVal.indexOf('.');
if (pointIndex !== -1) {
const pointAndBefore = stringVal.substring(0, pointIndex + 1);
const afterPoint = stringVal.substring(pointIndex + 1);
// removing all points after the first
stringVal = `${pointAndBefore}${afterPoint.replace(/\./g, '')}`;
}
const float = parseFloat(stringVal);
if (isNaN(float)) {
// fallback to emptying the input if anything goes south
setInputValue('');
return;
}
setInputValue(stringVal);
}
My pure (animated) Javascript solution:
function gototop() {
if (window.scrollY>0) {
window.scrollTo(0,window.scrollY-20)
setTimeout("gototop()",10)
}
}
Explanation:
window.scrollY
is a variable maintained by the browser of the amount of pixels from the top that the window has been scrolled by.
window.scrollTo(x,y)
is a function that scrolls the window a specific amount of pixels on the x axis and on the y axis.
Thus, window.scrollTo(0,window.scrollY-20)
moves the page 20 pixels towards the top.
The setTimeout
calls the function again in 10 milliseconds so that we can then move it another 20 pixels (animated), and the if
statement checks if we still need to scroll.
Note: ||= does not exist. (logical or) You can use
y= y || expr; // expr is NOT evaluated if y==true
or
y = expr ? true : y; // expr is always evaluated.
If what you're looking for is simply to blur the image edges you can simply use the box-shadow with an inset.
Working example: http://jsfiddle.net/d9Q5H/1/
HTML:
<div class="image-blurred-edge"></div>
CSS
.image-blurred-edge {
background-image: url('http://lorempixel.com/200/200/city/9');
width: 200px;
height: 200px;
/* you need to match the shadow color to your background or image border for the desired effect*/
box-shadow: 0 0 8px 8px white inset;
}
All in all, I'd say that MD5 in addition to the file name is absolutely safe. SHA-256 would just be slower and harder to handle because of its size.
You could also use something less secure than MD5 without any problem. If nobody tries to hack your file integrity this is safe, too.
You'll have to configure the server to interpret .html
files as .php
files. This configuration is different depending on the server software. This will also add an extra step to the server and will slow down response on all your pages and is probably not ideal.
Say this is your xml with spinner entries (ie. titles) and values:
<resources>
<string-array name="size_entries">
<item>Small</item>
<item>Medium</item>
<item>Large</item>
</string-array>
<string-array name="size_values">
<item>12</item>
<item>16</item>
<item>20</item>
</string-array>
</resources>
and this is your spinner:
<Spinner
android:id="@+id/size_spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:entries="@array/size_entries" />
Then in your code to get the entries:
Spinner spinner = (Spinner) findViewById(R.id.size_spinner);
String size = spinner.getSelectedItem().toString(); // Small, Medium, Large
and to get the values:
int spinner_pos = spinner.getSelectedItemPosition();
String[] size_values = getResources().getStringArray(R.array.size_values);
int size = Integer.valueOf(size_values[spinner_pos]); // 12, 16, 20
Just throw everything you read into a MemoryStream
and get the byte array in the end. As noted, you should be reading from the underlying stream to get the raw bytes.
var bytes = default(byte[]);
using (var memstream = new MemoryStream())
{
var buffer = new byte[512];
var bytesRead = default(int);
while ((bytesRead = reader.BaseStream.Read(buffer, 0, buffer.Length)) > 0)
memstream.Write(buffer, 0, bytesRead);
bytes = memstream.ToArray();
}
Or if you don't want to manage the buffers:
var bytes = default(byte[]);
using (var memstream = new MemoryStream())
{
reader.BaseStream.CopyTo(memstream);
bytes = memstream.ToArray();
}
To check if a folder contains at least one file
>nul 2>nul dir /a-d "folderName\*" && (echo Files exist) || (echo No file found)
To check if a folder or any of its descendents contain at least one file
>nul 2>nul dir /a-d /s "folderName\*" && (echo Files exist) || (echo No file found)
To check if a folder contains at least one file or folder.
Note addition of /a
option to enable finding of hidden and system files/folders.
dir /b /a "folderName\*" | >nul findstr "^" && (echo Files and/or Folders exist) || (echo No File or Folder found)
To check if a folder contains at least one folder
dir /b /ad "folderName\*" | >nul findstr "^" && (echo Folders exist) || (echo No folder found)
Add this in your build.gradle
configurations.all {
exclude group: 'org.springframework.boot', module: 'spring-boot-starter-tomcat'
exclude group: 'org.springframework.boot', module: 'spring-boot-starter-logging'
exclude group: 'org.springframework.boot', module: 'logback-classic'
}
With quotes around the date:
mysql> CALL insertEvent('2012.01.01 12:12:12');
in .htaccess file add following line to restrict http access
SSLRequireSSL
Here is the code I use. You should be able to adapt it to your needs.
function process_test_json() {
var jsonDataArr = { "Errors":[],"Success":true,"Data":{"step0":{"collectionNameStr":"dei_ideas_org_Private","url_root":"http:\/\/192.168.1.128:8500\/dei-ideas_org\/","collectionPathStr":"C:\\ColdFusion8\\wwwroot\\dei-ideas_org\\wwwrootchapter0-2\\verity_collections\\","writeVerityLastFileNameStr":"C:\\ColdFusion8\\wwwroot\\dei-ideas_org\\wwwroot\\chapter0-2\\VerityLastFileName.txt","doneFlag":false,"state_dbrec":{},"errorMsgStr":"","fileroot":"C:\\ColdFusion8\\wwwroot\\dei-ideas_org\\wwwroot"}}};
var htmlStr= "<h3 class='recurse_title'>[jsonDataArr] struct is</h3> " + recurse( jsonDataArr );
alert( htmlStr );
$( document.createElement('div') ).attr( "class", "main_div").html( htmlStr ).appendTo('div#out');
$("div#outAsHtml").text( $("div#out").html() );
}
function recurse( data ) {
var htmlRetStr = "<ul class='recurseObj' >";
for (var key in data) {
if (typeof(data[key])== 'object' && data[key] != null) {
htmlRetStr += "<li class='keyObj' ><strong>" + key + ":</strong><ul class='recurseSubObj' >";
htmlRetStr += recurse( data[key] );
htmlRetStr += '</ul ></li >';
} else {
htmlRetStr += ("<li class='keyStr' ><strong>" + key + ': </strong>"' + data[key] + '"</li >' );
}
};
htmlRetStr += '</ul >';
return( htmlRetStr );
}
</script>
</head><body>
<button onclick="process_test_json()" >Run process_test_json()</button>
<div id="out"></div>
<div id="outAsHtml"></div>
</body>
As string[]
implements IEnumerable
IEnumerable<string> m_oEnum = new string[] {"1","2","3"}
pimvdb's answer implemented in python:
def DecodedCharArrayFromByteStreamIn(stringStreamIn):
#turn string values into opererable numeric byte values
byteArray = [ord(character) for character in stringStreamIn]
datalength = byteArray[1] & 127
indexFirstMask = 2
if datalength == 126:
indexFirstMask = 4
elif datalength == 127:
indexFirstMask = 10
masks = [m for m in byteArray[indexFirstMask : indexFirstMask+4]]
indexFirstDataByte = indexFirstMask + 4
decodedChars = []
i = indexFirstDataByte
j = 0
while i < len(byteArray):
decodedChars.append( chr(byteArray[i] ^ masks[j % 4]) )
i += 1
j += 1
return decodedChars
An Example of usage:
fromclient = '\x81\x8c\xff\xb8\xbd\xbd\xb7\xdd\xd1\xd1\x90\x98\xea\xd2\x8d\xd4\xd9\x9c'
# this looks like "?ŒOÇ¿¢gÓ ç\Ð=«ož" in unicode, received by server
print DecodedCharArrayFromByteStreamIn(fromclient)
# ['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '!']
I think this is what you are looking for: jquery-html5-placeholder-fix
This solution uses feature detection (via modernizr) to determine if placeholder is supported. If not, adds support (via jQuery).
Your service must answer an OPTIONS
request with headers like these:
Access-Control-Allow-Origin: [the same origin from the request]
Access-Control-Allow-Methods: GET, POST, PUT
Access-Control-Allow-Headers: [the same ACCESS-CONTROL-REQUEST-HEADERS from request]
Here is a good doc: http://www.html5rocks.com/en/tutorials/cors/#toc-adding-cors-support-to-the-server
As of Python 2.7 (or 3.1 respectively) you can write
with open('a', 'w') as a, open('b', 'w') as b:
do_something()
In earlier versions of Python, you can sometimes use
contextlib.nested()
to nest context managers. This won't work as expected for opening multiples files, though -- see the linked documentation for details.
In the rare case that you want to open a variable number of files all at the same time, you can use contextlib.ExitStack
, starting from Python version 3.3:
with ExitStack() as stack:
files = [stack.enter_context(open(fname)) for fname in filenames]
# Do something with "files"
Most of the time you have a variable set of files, you likely want to open them one after the other, though.
The easiest way is probably with VLOOKUP()
. This will require the 2nd worksheet to have the employee number column sorted though. In newer versions of Excel, apparently sorting is no longer required.
For example, if you had a "Sheet2" with two columns - A = the employee number, B = the employee's name, and your current worksheet had employee numbers in column D and you want to fill in column E, in cell E2, you would have:
=VLOOKUP($D2, Sheet2!$A$2:$B$65535, 2, FALSE)
Then simply fill this formula down the rest of column D.
Explanation:
$D2
specifies the value to search for.Sheet2!$A$2:$B$65535
specifies the range of cells to search in. Excel will search for the value in the first column of this range (in this case Sheet2!A2:A65535
). Note I am assuming you have a header cell in row 1.2
specifies a 1-based index of the column to return from within the searched range. The value of 2
will return the second column in the range Sheet2!$A$2:$B$65535
, namely the value of the B
column.FALSE
says to only return exact matches.Get-WmiObject Win32_Processor | Select LoadPercentage | Format-List
This gives you CPU load.
Get-WmiObject Win32_Processor | Measure-Object -Property LoadPercentage -Average | Select Average
Using pure Java:
public static boolean isToday(Date date){
Calendar today = Calendar.getInstance();
Calendar specifiedDate = Calendar.getInstance();
specifiedDate.setTime(date);
return today.get(Calendar.DAY_OF_MONTH) == specifiedDate.get(Calendar.DAY_OF_MONTH)
&& today.get(Calendar.MONTH) == specifiedDate.get(Calendar.MONTH)
&& today.get(Calendar.YEAR) == specifiedDate.get(Calendar.YEAR);
}
try Parsing and Formatting
Take an example Parsing
String input = ...;
try {
DateTimeFormatter formatter =
DateTimeFormatter.ofPattern("MMM d yyyy");
LocalDate date = LocalDate.parse(input, formatter);
System.out.printf("%s%n", date);
}
catch (DateTimeParseException exc) {
System.out.printf("%s is not parsable!%n", input);
throw exc; // Rethrow the exception.
}
Formatting
ZoneId leavingZone = ...;
ZonedDateTime departure = ...;
try {
DateTimeFormatter format = DateTimeFormatter.ofPattern("MMM d yyyy hh:mm a");
String out = departure.format(format);
System.out.printf("LEAVING: %s (%s)%n", out, leavingZone);
}
catch (DateTimeException exc) {
System.out.printf("%s can't be formatted!%n", departure);
throw exc;
}
The output for this example, which prints both the arrival and departure time, is as follows:
LEAVING: Jul 20 2013 07:30 PM (America/Los_Angeles)
ARRIVING: Jul 21 2013 10:20 PM (Asia/Tokyo)
For more details check this page- https://docs.oracle.com/javase/tutorial/datetime/iso/format.html
In latin1 each character is exactly one byte long. In utf8 a character can consist of more than one byte. Consequently utf8 has more characters than latin1 (and the characters they do have in common aren't necessarily represented by the same byte/bytesequence).
Adding the data-position="fixed" and adding the below style in the css will fix the issue z-index: 1;
Bootstrap 4
Create a responsive navbar sidebar "drawer" in Bootstrap 4?
Bootstrap horizontal menu collapse to sidemenu
Bootstrap 3
I think what you're looking for is generally known as an "off-canvas" layout. Here is the standard off-canvas example from the official Bootstrap docs: http://getbootstrap.com/examples/offcanvas/
The "official" example uses a right-side sidebar the toggle off and on separately from the top navbar menu. I also found these off-canvas variations that slide in from the left and may be closer to what you're looking for..
http://www.bootstrapzero.com/bootstrap-template/off-canvas-sidebar http://www.bootstrapzero.com/bootstrap-template/facebook
Amazingly, Unix and Linux do not actually have a place to set global environment variables. The best you can do is arrange for any specific shell to have a site-specific initialization.
If you put it in /etc/profile
, that will take care of things for most posix-compatible shell users. This is probably "good enough" for non-critical purposes.
But anyone with a csh
or tcsh
shell won't see it, and I don't believe csh
has a global initialization file.
HTML Component
<input type="text" [formControl]="txtValue">
TS Component
public txtValue = new FormControl('', { validators:[Validators.required] });
We can use this method to save using API. LearnersModules is the module file on our Angular files SaveSampleExams is the service file is one function method.
> this.service.SaveSampleExams(LearnersModules).subscribe(
> (data) => {
> this.dataSaved = true;
> LearnersModules.txtValue = this.txtValue.value;
> });
If you need to support more than one format you will have to pattern match your input and parse accordingly.
final DateFormat fmt;
if (dateString.endsWith("Z")) {
fmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
} else {
fmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
}
I'd guess you're dealing with a bug in the API you're using which has quoted the Z
timezone date pattern somewhere...
With the render
method potentially deprecating the returned value, the recommended approach is now to attach a callback ref to the root element. Like this:
ReactDOM.render( <Hello name="World" ref={(element) => {window.helloComponent = element}}/>, document.getElementById('container'));
which we can then access using window.helloComponent, and any of its methods can be accessed with window.helloComponent.METHOD.
Here's a full example:
var onButtonClick = function() {_x000D_
window.helloComponent.alertMessage();_x000D_
}_x000D_
_x000D_
class Hello extends React.Component {_x000D_
alertMessage() {_x000D_
alert(this.props.name);_x000D_
}_x000D_
_x000D_
render() {_x000D_
return React.createElement("div", null, "Hello ", this.props.name);_x000D_
}_x000D_
};_x000D_
_x000D_
ReactDOM.render( <Hello name="World" ref={(element) => {window.helloComponent = element}}/>, document.getElementById('container'));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="container"></div>_x000D_
<button onclick="onButtonClick()">Click me!</button>
_x000D_
I had the same symptoms as described here. I could connect once to a bluetooth printer but subsequent connects failed with "socket closed" no matter what I did.
I found it a bit strange that the workarounds described here would be necessary. After going through my code I found that I had forgot to close the socket's InputStream and OutputSteram and not terminated the ConnectedThreads properly.
The ConnectedThread I use is the same as in the example here:
http://developer.android.com/guide/topics/connectivity/bluetooth.html
Note that ConnectThread and ConnectedThread are two different classes.
Whatever class that starts the ConnectedThread must call interrupt() and cancel() on the thread. I added mmInStream.close() and mmOutStream.close() in the ConnectedTread.cancel() method.
After closing the threads/streams/sockets properly I could create new sockets without any problem.
If you don't use inplace=True or you use inplace=False you basically get back a copy.
So for instance:
testdf.sort_values(inplace=True, by='volume', ascending=False)
will alter the structure with the data sorted in descending order.
then:
testdf2 = testdf.sort_values( by='volume', ascending=True)
will make testdf2 a copy. the values will all be the same but the sort will be reversed and you will have an independent object.
then given another column, say LongMA and you do:
testdf2.LongMA = testdf2.LongMA -1
the LongMA column in testdf will have the original values and testdf2 will have the decrimented values.
It is important to keep track of the difference as the chain of calculations grows and the copies of dataframes have their own lifecycle.
Not mentioned above but using max-width
or max-height
on the canvas element is also a possibility.
/etc/launchd.conf is not used in OS X v10.10 (Yosemite), OS X v10.11 (El Capitan), macOS v10.12 (Sierra), or macOS v10.13 (High Sierra).
From the launchctl
man page:
/etc/launchd.conf file is no longer consulted for subcommands to run during early boot time;
this functionality was removed for security considerations.
The method described in this Ask Different answer works for me (after a reboot): applications launched from the Dock or from Spotlight inherit environment variables that I set in ~/Library/LaunchAgents/my.startup.plist
. (In my case, I needed to set LANG
, to en_US.UTF-8
, for a Sublime Text plugin.)
I have found the designer "update from database" can only handle small changes. If you have deleted tables, changed foreign keys or (gasp) changed the signature of a stored procedure with a function mapping, you will eventually get to such a messed up state you will have to either delete all the entities and "add from database" or simply delete the edmx resource and start over.
This is a quirk of the C grammar. A label (Cleanup:
) is not allowed to appear immediately before a declaration (such as char *str ...;
), only before a statement (printf(...);
). In C89 this was no great difficulty because declarations could only appear at the very beginning of a block, so you could always move the label down a bit and avoid the issue. In C99 you can mix declarations and code, but you still can't put a label immediately before a declaration.
You can put a semicolon immediately after the label's colon (as suggested by Renan) to make there be an empty statement there; this is what I would do in machine-generated code. Alternatively, hoist the declaration to the top of the function:
int main (void)
{
char *str;
printf("Hello ");
goto Cleanup;
Cleanup:
str = "World\n";
printf("%s\n", str);
return 0;
}
https://stackoverflow.com/a/33368029/15789
I have posted an answer here.
Open a Windows command window, and execute this script. If there is a change in your working directory, it will open a bash terminal in your working directory, and display the current git status. It keeps the bash window open, by calling exec bash.
If you have multiple projects you may create copies of this script with different project folder, and call it from a main batch script.
IN objective-c, if you are dealing with regular char arrays (instead of pointers to NSString) you could also use:
printf("%.02f", your_float_var);
OTOH, if what you want is to store that value on a char array you could use:
sprintf(your_char_ptr, "%.02f", your_float_var);
import re
url = '<p>Hello World</p><a href="http://example.com">More Examples</a><a href="http://example2.com">Even More Examples</a>'
urls = re.findall('https?://(?:[-\w.]|(?:%[\da-fA-F]{2}))+', url)
>>> print urls
['http://example.com', 'http://example2.com']
When you say
foo = 'bar'
baz(foo)
you are not passing foo
to the baz
function. foo
is just a name used to represent a value, in this case 'bar'
, and that value is passed to the baz
function.
Yes, it's possible to install a specific version of Angular using npm:
npm install -g @angular/[email protected]
Next, you need to use the ng new command to create an Angular project based on the specific version you used when installing the CLI:
ng new your-project-name
This will generate a project based on Angular v8.3.19, the version which was specified when installing Angular CLI.
400 Bad request Error will be thrown due to incorrect authentication entries.
Note: Mostly due to Incorrect authentication entries due to spell changes will occur 400 Bad request.
String uri = http://my-rest-url.org/rest/account/{account};
Map<String, String> uriParam = new HashMap<>();
uriParam.put("account", "my_account");
UriComponents builder = UriComponentsBuilder.fromHttpUrl(uri)
.queryParam("pageSize","2")
.queryParam("page","0")
.queryParam("name","my_name").build();
HttpEntity<String> requestEntity = new HttpEntity<>(null, getHeaders());
ResponseEntity<String> strResponse = restTemplate.exchange(builder.toUriString(),HttpMethod.GET, requestEntity,
String.class,uriParam);
//final URL: http://my-rest-url.org/rest/account/my_account?pageSize=2&page=0&name=my_name
RestTemplate: Build dynamic URI using UriComponents (URI variable and Request parameters)
I tried this solution with Microsoft.SqlServer.Management but it didn't work well with .NET 4.0 so I wrote another solution using .NET libs framework only.
string script = File.ReadAllText(@"E:\someSqlScript.sql");
// split script on GO command
IEnumerable<string> commandStrings = Regex.Split(script, @"^\s*GO\s*$", RegexOptions.Multiline | RegexOptions.IgnoreCase);
Connection.Open();
foreach (string commandString in commandStrings)
{
if (!string.IsNullOrWhiteSpace(commandString.Trim()))
{
using(var command = new SqlCommand(commandString, Connection))
{
command.ExecuteNonQuery();
}
}
}
Connection.Close();
You need to add the URL to your app:
That's all and you are done. Make sure that the app's URL is the same from where you're logging in.
In my case I had to uninstall hyper-v, restart pc, and run docker again.
Its a simple xml design. It looks like iOS switch, check this below image
You need to create custom_thumb.xml and custom_track.xml
This is my switch,I need a very big switch so added layout_width/layout_height parameter
<androidx.appcompat.widget.SwitchCompat
android:id="@+id/swOnOff"
android:layout_width="@dimen/_200sdp"
android:layout_marginStart="@dimen/_50sdp"
android:layout_marginEnd="@dimen/_50sdp"
android:layout_marginTop="@dimen/_30sdp"
android:layout_gravity="center"
app:showText="true"
android:textSize="@dimen/_20ssp"
android:fontFamily="@font/opensans_bold"
app:track="@drawable/custom_track"
android:thumb="@drawable/custom_thumb"
android:layout_height="@dimen/_120sdp"/>
Now create custom_thumb.xml
<?xml version="1.0" encoding="utf-8"?>
<selector
xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="false">
<shape android:shape="oval">
<solid android:color="#ffffff"/>
<size android:width="@dimen/_100sdp"
android:height="@dimen/_100sdp"/>
<stroke android:width="1dp"
android:color="#8c8c8c"/>
</shape>
</item>
<item android:state_checked="true">
<shape android:shape="oval">
<solid android:color="#ffffff"/>
<size android:width="@dimen/_100sdp"
android:height="@dimen/_100sdp"/>
<stroke android:width="1dp"
android:color="#34c759"/>
</shape>
</item>
</selector>
Now create custom_track.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="false">
<shape android:shape="rectangle">
<corners android:radius="@dimen/_100sdp" />
<solid android:color="#ffffff" />
<stroke android:color="#8c8c8c" android:width="1dp"/>
<size android:height="20dp" />
</shape>
</item>
<item android:state_checked="true">
<shape android:shape="rectangle">
<corners android:radius="@dimen/_100sdp" />
<solid android:color="#34c759" />
<stroke android:color="#8c8c8c" android:width="1dp"/>
<size android:height="20dp" />
</shape>
</item>
</selector>
you should change cr_date(str) to datetime object then you 'll change the date to the specific format:
cr_date = '2013-10-31 18:23:29.000227'
cr_date = datetime.datetime.strptime(cr_date, '%Y-%m-%d %H:%M:%S.%f')
cr_date = cr_date.strftime("%m/%d/%Y")
An easily broken way to do this is :
<?php
// Send the headers
header('Content-type: text/xml');
header('Pragma: public');
header('Cache-control: private');
header('Expires: -1');
echo "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
echo '<xml>';
// echo some dynamically generated content here
/*
<track>
<path>song_path</path>
<title>track_number - track_title</title>
</track>
*/
echo '</xml>';
?>
save it as .php
Check your error log file and then use the tail command as:
tail -200f /var/log/redis_6379.log
or
tail -200f /var/log/redis.log
According to your error file name..
I switched over to the managed ODP.NET assemblies from Oracle. I also had to purge all the files from the IIS web apps that were using the older assemblies. Now I don't get any conflicts regarding 32 vs 64 bit versions when I debug in IIS Express vs IIS. See the following article.
Resize to fit the container, get scale factor, scale down percentage control
$(function () {
let ParentHeight = 200;
let ParentWidth = 300;
$("#Parent").width(ParentWidth).height(ParentHeight);
$("#ParentHeight").html(ParentHeight);
$("#ParentWidth").html(ParentWidth);
var RatioOfParent = ParentHeight / ParentWidth;
$("#ParentAspectRatio").html(RatioOfParent);
let ChildHeight = 2000;
let ChildWidth = 4000;
var RatioOfChild = ChildHeight / ChildWidth;
$("#ChildAspectRatio").html(RatioOfChild);
let ScaleHeight = ParentHeight / ChildHeight;
let ScaleWidth = ParentWidth / ChildWidth;
let Scale = Math.min(ScaleHeight, ScaleWidth);
$("#ScaleFactor").html(Scale);
// old scale
//ChildHeight = ChildHeight * Scale;
//ChildWidth = ChildWidth * Scale;
// reduce scale by 10%, you can change the percentage
let ScaleDownPercentage = 10;
let CalculatedScaleValue = Scale * (ScaleDownPercentage / 100);
$("#CalculatedScaleValue").html(CalculatedScaleValue);
// new scale
let NewScale = (Scale - CalculatedScaleValue);
ChildHeight = ChildHeight * NewScale;
ChildWidth = ChildWidth * NewScale;
$("#Child").width(ChildWidth).height(ChildHeight);
$("#ChildHeight").html(ChildHeight);
$("#ChildWidth").html(ChildWidth);
});
_x000D_
#Parent {
background-color: grey;
}
#Child {
background-color: red;
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="Parent">
<div id="Child"></div>
</div>
<table>
<tr>
<td>Parent Aspect Ratio</td>
<td id="ParentAspectRatio"></td>
</tr>
<tr>
<td>Child Aspect Ratio</td>
<td id="ChildAspectRatio"></td>
</tr>
<tr>
<td>Scale Factor</td>
<td id="ScaleFactor"></td>
</tr>
<tr>
<td>Calculated Scale Value</td>
<td id="CalculatedScaleValue"></td>
</tr>
<tr>
<td>Parent Height</td>
<td id="ParentHeight"></td>
</tr>
<tr>
<td>Parent Width</td>
<td id="ParentWidth"></td>
</tr>
<tr>
<td>Child Height</td>
<td id="ChildHeight"></td>
</tr>
<tr>
<td>Child Width</td>
<td id="ChildWidth"></td>
</tr>
</table>
_x000D_
Please try the below query. Use sys.columns to get the details :-
SELECT c.name AS ColName, t.name AS TableName
FROM sys.columns c
JOIN sys.tables t ON c.object_id = t.object_id
WHERE c.name LIKE '%MyCol%';
You can try something like this
IFNULL(NULLIF(X, '' ), 0)
Attribute X is assumed to be empty if it is an empty String, so after that you can declare as a zero instead of last value. In another case, it would remain its original value.
Anyway, just to give another way to do that.
This is pretty clear, actually. Many folks learn it quickly. You can use a comment to help them.
new_index = max(0, min(new_index, len(mylist)-1))
Since this is an old thread just adding an update:
If you run just npm install mysql
, you need to be in the same directory that your run your server. I would advise to do it as in one of the following examples:
npm install -g mysql
1- Add it to your package.json
in the dependencies:
"dependencies": {
"mysql": "~2.3.2",
...
2- run npm install
Note that for connections to happen you will also need to be running the mysql server (which is node independent)
There are a bunch of tutorials out there that explain this, and it is a bit dependent on operative system. Just go to google and search for how to install mysql server [Ubuntu|MacOSX|Windows]
. But in a sentence: you have to go to http://www.mysql.com/downloads/ and install it.
That means you must install simplejson
. On newer versions of python, it was included by default into python's distribution, and renamed to json
. So if you are on python 2.6+ you should change all instances of simplejson
to json
.
For a quick fix you could also edit the file and change the line:
import simplejson
to:
import json as simplejson
and hopefully things will work.
Just in case anyone else stumbled on this question while looking for a way to replace a string across multiple files, it is Command+Shift+F
You should use the class name like this
$(document).ready(function(){
$('input.addCheck').prop('checked',true);
});
Try Using this a live demo
Had to look it up in the specs:
Class's getResource() - documentation states the difference:
This method delegates the call to its class loader, after making these changes to the resource name: if the resource name starts with "/", it is unchanged; otherwise, the package name is prepended to the resource name after converting "." to "/". If this object was loaded by the bootstrap loader, the call is delegated to ClassLoader.getSystemResource.
For person who are afraid on re-creating AppStore distribution certificate Apple documentation says:
Important: Re-creating your development or distribution certificates doesn’t affect apps that you’ve submitted to the App Store nor does it affect your ability to update them.
But it affects apps for Apple Developer Enterprise ecosystem.
The answers from freedompeace, Kiyarash and Sam Vloeberghs:
.rar application/x-rar-compressed, application/octet-stream
.zip application/zip, application/octet-stream, application/x-zip-compressed, multipart/x-zip
I would do a check on the file name too. Here is how you could check if the file is a RAR or ZIP file. I tested it by creating a quick command line application.
<?php
if (isRarOrZip($argv[1])) {
echo 'It is probably a RAR or ZIP file.';
} else {
echo 'It is probably not a RAR or ZIP file.';
}
function isRarOrZip($file) {
// get the first 7 bytes
$bytes = file_get_contents($file, FALSE, NULL, 0, 7);
$ext = strtolower(substr($file, - 4));
// RAR magic number: Rar!\x1A\x07\x00
// http://en.wikipedia.org/wiki/RAR
if ($ext == '.rar' and bin2hex($bytes) == '526172211a0700') {
return TRUE;
}
// ZIP magic number: none, though PK\003\004, PK\005\006 (empty archive),
// or PK\007\008 (spanned archive) are common.
// http://en.wikipedia.org/wiki/ZIP_(file_format)
if ($ext == '.zip' and substr($bytes, 0, 2) == 'PK') {
return TRUE;
}
return FALSE;
}
Notice that it still won't be 100% certain, but it is probably good enough.
$ rar.exe l somefile.zip
somefile.zip is not RAR archive
But even WinRAR detects non RAR files as SFX archives:
$ rar.exe l somefile.srr
SFX Volume somefile.srr
I think you just have incorrect casing in the format string. According to the documentation this should work for you: MM/DD/YYYY
Here's a solution that should always work and doesn't remove the hash.
let currentPage = new URL(window.location.href);
currentPage.searchParams.set('r', (+new Date * Math.random()).toString(36).substring(0, 5));
window.location.href = currentPage.href;
Remove the name
param from the class declaration. The init method is used to pass arguments to a class at creation.
class Person(object):
def __init__(self, name):
self.name = name
me = Person("TheLazyScripter")
print me.name
class Exception
{
public Exception(string message)
{
[...]
}
}
class MyExceptionClass : Exception
{
public MyExceptionClass(string message, string extraInfo)
: base(message)
{
[...]
}
}
document.getElementById("serverTime").innerHTML = ...;
Analog of the @synchronized
directive from Objective-C can have an arbitrary return type and nice rethrows
behaviour in Swift.
// Swift 3
func synchronized<T>(_ lock: AnyObject, _ body: () throws -> T) rethrows -> T {
objc_sync_enter(lock)
defer { objc_sync_exit(lock) }
return try body()
}
The use of the defer
statement lets directly return a value without introducing a temporary variable.
In Swift 2 add the @noescape
attribute to the closure to allow more optimisations:
// Swift 2
func synchronized<T>(lock: AnyObject, @noescape _ body: () throws -> T) rethrows -> T {
objc_sync_enter(lock)
defer { objc_sync_exit(lock) }
return try body()
}
Based on the answers from GNewc [1] (where I like arbitrary return type) and Tod Cunningham [2] (where I like defer
).
By default, unlike an exception, a warning doesn't interrupt.
After import warnings
, it is possible to specify a Warnings class when generating a warning. If one is not specified, it is literally UserWarning
by default.
>>> warnings.warn('This is a default warning.')
<string>:1: UserWarning: This is a default warning.
To simply use a preexisting class instead, e.g. DeprecationWarning
:
>>> warnings.warn('This is a particular warning.', DeprecationWarning)
<string>:1: DeprecationWarning: This is a particular warning.
Creating a custom warning class is similar to creating a custom exception class:
>>> class MyCustomWarning(UserWarning):
... pass
...
... warnings.warn('This is my custom warning.', MyCustomWarning)
<string>:1: MyCustomWarning: This is my custom warning.
For testing, consider assertWarns
or assertWarnsRegex
.
As an alternative, especially for standalone applications, consider the logging
module. It can log messages having a level of debug, info, warning, error, etc. Log messages having a level of warning or higher are by default printed to stderr.
try this Simple Automatic Number Plate Recognition System
Open source and written with C#
I think there is a semantic problem here. In my view, a user can have a (but only one) favourite recipe to prepare a specific menu. (The OP has menu and recipe mixed up; if I am wrong: please interchange MenuId and RecipeId below) That implies that {user,menu} should be a unique key in this table. And it should point to exactly one recipe. If the user has no favourite recipe for this specific menu no row should exist for this {user,menu} key pair. Also: the surrogate key (FaVouRiteId) is superfluous: composite primary keys are perfectly valid for relational-mapping tables.
That would lead to the reduced table definition:
CREATE TABLE Favorites
( UserId uuid NOT NULL REFERENCES users(id)
, MenuId uuid NOT NULL REFERENCES menus(id)
, RecipeId uuid NOT NULL REFERENCES recipes(id)
, PRIMARY KEY (UserId, MenuId)
);
To show only running containers use the given command:
docker ps
To show all containers use the given command:
docker ps -a
To show the latest created container (includes all states) use the given command:
docker ps -l
To show n last created containers (includes all states) use the given command:
docker ps -n=-1
To display total file sizes use the given command:
docker ps -s
The content presented above is from docker.com.
In the new version of Docker, commands are updated, and some management commands are added:
docker container ls
It is used to list all the running containers.
docker container ls -a
And then, if you want to clean them all,
docker rm $(docker ps -aq)
It is used to list all the containers created irrespective of its state.
And to stop all the Docker containers (force)
docker rm -f $(docker ps -a -q)
Here the container is the management command.
Use the ensure_ascii=False
switch to json.dumps()
, then encode the value to UTF-8 manually:
>>> json_string = json.dumps("??? ????", ensure_ascii=False).encode('utf8')
>>> json_string
b'"\xd7\x91\xd7\xa8\xd7\x99 \xd7\xa6\xd7\xa7\xd7\x9c\xd7\x94"'
>>> print(json_string.decode())
"??? ????"
If you are writing to a file, just use json.dump()
and leave it to the file object to encode:
with open('filename', 'w', encoding='utf8') as json_file:
json.dump("??? ????", json_file, ensure_ascii=False)
Caveats for Python 2
For Python 2, there are some more caveats to take into account. If you are writing this to a file, you can use io.open()
instead of open()
to produce a file object that encodes Unicode values for you as you write, then use json.dump()
instead to write to that file:
with io.open('filename', 'w', encoding='utf8') as json_file:
json.dump(u"??? ????", json_file, ensure_ascii=False)
Do note that there is a bug in the json
module where the ensure_ascii=False
flag can produce a mix of unicode
and str
objects. The workaround for Python 2 then is:
with io.open('filename', 'w', encoding='utf8') as json_file:
data = json.dumps(u"??? ????", ensure_ascii=False)
# unicode(data) auto-decodes data to unicode if str
json_file.write(unicode(data))
In Python 2, when using byte strings (type str
), encoded to UTF-8, make sure to also set the encoding
keyword:
>>> d={ 1: "??? ????", 2: u"??? ????" }
>>> d
{1: '\xd7\x91\xd7\xa8\xd7\x99 \xd7\xa6\xd7\xa7\xd7\x9c\xd7\x94', 2: u'\u05d1\u05e8\u05d9 \u05e6\u05e7\u05dc\u05d4'}
>>> s=json.dumps(d, ensure_ascii=False, encoding='utf8')
>>> s
u'{"1": "\u05d1\u05e8\u05d9 \u05e6\u05e7\u05dc\u05d4", "2": "\u05d1\u05e8\u05d9 \u05e6\u05e7\u05dc\u05d4"}'
>>> json.loads(s)['1']
u'\u05d1\u05e8\u05d9 \u05e6\u05e7\u05dc\u05d4'
>>> json.loads(s)['2']
u'\u05d1\u05e8\u05d9 \u05e6\u05e7\u05dc\u05d4'
>>> print json.loads(s)['1']
??? ????
>>> print json.loads(s)['2']
??? ????
Try this, it works!
<div class="row">
<div class="center">
<div class="col-xs-12 col-sm-4">
<p>hi 1!</p>
</div>
<div class="col-xs-12 col-sm-4">
<p>hi 2!</p>
</div>
<div class="col-xs-12 col-sm-4">
<p>hi 3!</p>
</div>
</div>
</div>
Then, in css define the width of center div and center in a document:
.center {
margin: 0 auto;
width: 80%;
}
If you're looking for a pure css option, try using the :focus pseudo class.
#style {
background-color: red;
}
#style:focus {
background-color:yellow;
}
You could use JavaScript. Either put the code inline, into a function or use jQuery.
Inline:
<a href="deletelink" onclick="return confirm('Are you sure?')">Delete</a>
In a function:
<a href="deletelink" onclick="return checkDelete()">Delete</a>
and then put this in <head>
:
<script language="JavaScript" type="text/javascript">
function checkDelete(){
return confirm('Are you sure?');
}
</script>
This one has more work, but less file size if the list is long.
With jQuery:
<a href="deletelink" class="delete">Delete</a>
And put this in <head>
:
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script language="JavaScript" type="text/javascript">
$(document).ready(function(){
$("a.delete").click(function(e){
if(!confirm('Are you sure?')){
e.preventDefault();
return false;
}
return true;
});
});
</script>