The easiest answer is given by W3schools. https://www.w3schools.com/html/html_youtube.asp
<iframe width="640" height="520"
src="https://www.youtube.com/embed/<VideoID>">
</iframe>
I have experienced the same error when trying to build the message below with jQuery. The circular reference happens when reviewerName
was being mistakenly assigned to msg.detail.reviewerName
. JQuery's .val() fixed the issue, see last line.
var reviewerName = $('reviewerName'); // <input type="text" id="taskName" />;
var msg = {"type":"A", "detail":{"managerReview":true} };
msg.detail.reviewerName = reviewerName; // Error
msg.detail.reviewerName = reviewerName.val(); // Fixed
In InnoDB you have START TRANSACTION;
, which in this engine is the officialy recommended way to do transactions, instead of SET AUTOCOMMIT = 0;
(don't use SET AUTOCOMMIT = 0;
for transactions in InnoDB unless it is for optimizing read only transactions). Commit with COMMIT;
.
You might want to use SET AUTOCOMMIT = 0;
in InnoDB for testing purposes, and not precisely for transactions.
In MyISAM you do not have START TRANSACTION;
. In this engine, use SET AUTOCOMMIT = 0;
for transactions. Commit with COMMIT;
or SET AUTOCOMMIT = 1;
(Difference explained in MyISAM example commentary below). You can do transactions this way in InnoDB too.
Source: http://dev.mysql.com/doc/refman/5.6/en/glossary.html#glos_autocommit
Examples of general use transactions:
/* InnoDB */
START TRANSACTION;
INSERT INTO table_name (table_field) VALUES ('foo');
INSERT INTO table_name (table_field) VALUES ('bar');
COMMIT; /* SET AUTOCOMMIT = 1 might not set AUTOCOMMIT to its previous state */
/* MyISAM */
SET AUTOCOMMIT = 0;
INSERT INTO table_name (table_field) VALUES ('foo');
INSERT INTO table_name (table_field) VALUES ('bar');
SET AUTOCOMMIT = 1; /* COMMIT statement instead would not restore AUTOCOMMIT to 1 */
You can view/copy/download a timecoded xml file of a youtube's closed captions file by accessing
http://video.google.com/timedtext?lang=[LANGUAGE]&v=[YOUTUBE VIDEO IDENTIFIER]
For example http://video.google.com/timedtext?lang=pt&v=WSVKbw7LC2w
NOTE: this method does not download autogenerated closed captions, even if you get the language right (maybe there's a special code for autogenerated languages).
Using AOP/AspectJ and @Loggable
annotation from jcabi-aspects you can do it easy and compact:
@Loggable(Loggable.DEBUG)
public String getSomeResult() {
// return some value
}
Every call to this method will be sent to SLF4J logging facility with DEBUG
logging level. And every log message will include execution time.
BTW you can pass the error message directly to sys.exit:
if len(sys.argv) < 2:
sys.exit('Usage: %s database-name' % sys.argv[0])
if not os.path.exists(sys.argv[1]):
sys.exit('ERROR: Database %s was not found!' % sys.argv[1])
The maximum values do not depend on Eclipse, it depends on your OS (and obviously on the physical memory available).
You may want to take a look at this question: Max amount of memory per java process in Windows?
Actually I just found out that there is even one more way of getting a country code, using the getSimCountryIso() method of TelephoneManager
:
TelephonyManager tm = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
String countryCode = tm.getSimCountryIso();
Since it is the sim code it also should not change when traveling to other countries.
There is a tool called MySQL Pivot table generator, it can help you create web based pivot table that you can later export to excel(if you like). it can work if your data is in a single table or in several tables .
All you need to do is to specify the data source of the columns (it supports dynamic columns), rows , the values in the body of the table and table relationship (if there are any)
The home page of this tool is http://mysqlpivottable.net
I looked for a C/C++ API for Google Voice for quite a while and never found anything close (the closest was a C# API). Since I really needed it, I decided to just write one myself:
http://github.com/mastermind202/GoogleVoice
I hope others find it useful. Feedback and suggestions welcome.
Here is a real world example. In this it is necessary to initialize the array foundFiles
first to zero length.
(As emphasized in other answers: This initializes not an element and especially not an element with index zero because that would mean the array had length 1. The array has zero length after this line!).
If the part = string[0]
is omitted, there is a compiler error!
This is because of the catch block without rethrow. The C# compiler recognizes the code path, that the function Directory.GetFiles()
can throw an Exception, so that the array could be uninitialized.
Before anyone says, not rethrowing the exception would be bad error handling: This is not true. Error handling has to fit the requirements.
In this case it is assumed that the program should continue in case of a directory which cannot be read, and not break- the best example is a function traversing through a directory structure. Here the error handling is just logging it. Of course this could be done better, e.g. collecting all directories with failed GetFiles(Dir)
calls in a list, but this will lead too far here.
It is enough to state that avoiding throw
is a valid scenario, and so the array has to be initialized to length zero. It would be enough to do this in the catch block, but this would be bad style.
The call to GetFiles(Dir)
resizes the array.
string[] foundFiles= new string[0];
string dir = @"c:\";
try
{
foundFiles = Directory.GetFiles(dir); // Remark; Array is resized from length zero
}
// Please add appropriate Exception handling yourself
catch (IOException)
{
Console.WriteLine("Log: Warning! IOException while reading directory: " + dir);
// throw; // This would throw Exception to caller and avoid compiler error
}
foreach (string filename in foundFiles)
Console.WriteLine("Filename: " + filename);
In the first class, sayHi()
is actually an instance method which you are calling as a static method and you get away with it because sayHi()
never refers to $this
.
Static functions are associated with the class, not an instance of the class. As such, $this
is not available from a static context ($this
isn't pointing to any object).
I still think using Join is simpler. Record the expected completion time (as Now+timeout), then, in a loop, do
if(!thread.Join(End-now))
throw new NotFinishedInTime();
An alternative to javax.comm
is the rxtx
library which supports more platforms than javax.comm
.
You need to understand, the component hierarchy you are having and how you are passing props, definitely your case is special and not usually encountered by the devs.
Parent Component -myProp-> Child Component -myProp-> Grandchild Component
If myProp is changed in parent component it will be reflected in the child component too.
And if myProp is changed in child component it will be reflected in grandchild component too.
So if myProp is changed in parent component then it will be reflected in grandchild component. (so far so good).
Therefore down the hierarchy you don't have to do anything props will be inherently reactive.
Now talking about going up in hierarchy
If myProp is changed in grandChild component it won't be reflected in the child component. You have to use .sync modifier in child and emit event from the grandChild component.
If myProp is changed in child component it won't be reflected in the parent component. You have to use .sync modifier in parent and emit event from the child component.
If myProp is changed in grandChild component it won't be reflected in the parent component (obviously). You have to use .sync modifier child and emit event from the grandchild component, then watch the prop in child component and emit an event on change which is being listened by parent component using .sync modifier.
Let's see some code to avoid confusion
Parent.vue
<template>
<div>
<child :myProp.sync="myProp"></child>
<input v-model="myProp"/>
<p>{{myProp}}</p>
</div>
</template>
<script>
import child from './Child.vue'
export default{
data(){
return{
myProp:"hello"
}
},
components:{
child
}
}
</script>
<style scoped>
</style>
Child.vue
<template>
<div> <grand-child :myProp.sync="myProp"></grand-child>
<p>{{myProp}}</p>
</div>
</template>
<script>
import grandChild from './Grandchild.vue'
export default{
components:{
grandChild
},
props:['myProp'],
watch:{
'myProp'(){
this.$emit('update:myProp',this.myProp)
}
}
}
</script>
<style>
</style>
Grandchild.vue
<template>
<div><p>{{myProp}}</p>
<input v-model="myProp" @input="changed"/>
</div>
</template>
<script>
export default{
props:['myProp'],
methods:{
changed(event){
this.$emit('update:myProp',this.myProp)
}
}
}
</script>
<style>
</style>
But after this you wont help notice the screaming warnings of vue saying
'Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders.'
Again as I mentioned earlier most of the devs don't encounter this issue, because it's an anti pattern. That's why you get this warning.
But in order to solve your issue (according to your design). I believe you have to do the above work around(hack to be honest). I still recommend you should rethink your design and make is less prone to bugs.
I hope it helps.
add HeaderStyle in your bound field:
<asp:BoundField HeaderText="UserId"
DataField="UserId"
SortExpression="UserId">
<HeaderStyle Width="200px" />
</asp:BoundField>
One possible PHP solution:
// load XML to SimpleXML
$x = simplexml_load_string($xmlstr);
// index it by title once
$index = array();
foreach ($x->CD as &$cd) {
$title = strtolower((string)$cd['title']);
if (!array_key_exists($title, $index)) $index[$title] = array();
$index[$title][] = &$cd;
}
// query the index
$result = $index[strtolower("EMPIRE BURLESQUE")];
The .cpp
file is configured to use precompiled header, therefore it must be included first (before iostream). For Visual Studio, it's name is usually "stdafx.h".
If there are no stdafx* files in your project, you need to go to this file's options and set it as “Not using precompiled headers”.
You should use CSS to align the textbox. The reason your code above does not work is because by default a div's width is the same as the container it's in, therefore in your example it is pushed below.
The following would work.
<td colspan="2" class="cell">
<asp:Label ID="Label6" runat="server" Text="Label"></asp:Label>
<asp:TextBox ID="TextBox3" runat="server" CssClass="righttextbox"></asp:TextBox>
</td>
In your CSS file:
.cell
{
text-align:left;
}
.righttextbox
{
float:right;
}
Have you tried the Interpolation syntax?
background: url(#{$get-path-to-assets}/site/background.jpg) repeat-x fixed 0 0;
The previous answers are all good, but they all show origin/master. These days, following the best practices, I rarely work directly on a master branch, let alone from origin repo.
So if you are like me who work in a branch, here are tips:
Or more simply, just use HEAD:
Using Tyler Dodge's excellent answer kept lagging on my iPad, so I added some throttling code, now it's quite smooth. There is some minimal skipping sometimes while scrolling.
// Uses document because document will be topmost level in bubbling
$(document).on('touchmove',function(e){
e.preventDefault();
});
var scrolling = false;
// Uses body because jquery on events are called off of the element they are
// added to, so bubbling would not work if we used document instead.
$('body').on('touchstart','.scrollable',function(e) {
// Only execute the below code once at a time
if (!scrolling) {
scrolling = true;
if (e.currentTarget.scrollTop === 0) {
e.currentTarget.scrollTop = 1;
} else if (e.currentTarget.scrollHeight === e.currentTarget.scrollTop + e.currentTarget.offsetHeight) {
e.currentTarget.scrollTop -= 1;
}
scrolling = false;
}
});
// Prevents preventDefault from being called on document if it sees a scrollable div
$('body').on('touchmove','.scrollable',function(e) {
e.stopPropagation();
});
Also, adding the following CSS fixes some rendering glitches (source):
.scrollable {
overflow: auto;
overflow-x: hidden;
-webkit-overflow-scrolling: touch;
}
.scrollable * {
-webkit-transform: translate3d(0,0,0);
}
In Swift 4.2 you can generate random numbers by calling the random()
method on whatever numeric type you want, providing the range you want to work with. For example, this generates a random number in the range 1 through 9, inclusive on both sides
let randInt = Int.random(in: 1..<10)
Also with other types
let randFloat = Float.random(in: 1..<20)
let randDouble = Double.random(in: 1...30)
let randCGFloat = CGFloat.random(in: 1...40)
I know this is an older question but here are the steps I used to get cassandra-driver
to actually install on Windows 7 / Python2. I have windows 10 / Python3 at home where I will test this tonight. I have confirmed this also works on Windows 10 with both Python 2 and 3.
Problem
Command "python setup.py egg_info" failed with error code 1 in c:\users\Frito\appdata\local\temp\pip-build-7dgmdc\cassandra-driver
TL;DR Solution
Solution (I'd love for someone to explain why this worked)
pip install cassandra-driver
and got the above error messagepip install --pre cassandra-driver
and got the following errordistutils.errors.DistutilsError: Setup script exited with error: Microsoft Visual C++ 9.0 is required (Unable to find vcvarsall.bat). Get it from http://aka.ms/vcpython27 Command "c:\users\Frito\.virtualenvs\symdash\scripts\python.exe -u -c "import setuptools, tokenize;__file__='c:\\users\\Frito\\appdata\\local\\temp\\pip-build-sesxxu\\cassandra-driver\\setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record c:\users\Frito\appdata\local\temp\pip-ujsxsk-record\install-record.txt --single-version-externally-managed --compile --install-headers c:\users\Frito\.virtualenvs\symdash\include\site\python2.7\cassandra-driver" failed with error code 1 in c:\users\Frito\appdata\local\temp\pip-build-sesxxu\cassandra-driver
Microsoft Visual C++ Compiler for Python 2.7
pip install --pre cassandra-driver
pip uninstall cassandra-driver
pip install cassandra-driver
To reiterate, I'm not really sure why this worked. Right now my two leading conclusions are that either the C++ compiler is required or that running the --pre
option the first time installed some dependencies that were missing from the 'regular' install. I'll update tonight after work when I have more details.
Comparing pointers is not portable, for example in DOS different pointer values points to the same location, comparison of the pointers returns false.
/*--{++:main.c}--------------------------------------------------*/
#include <dos.h>
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int val_a = 123;
int * ptr_0 = &val_a;
int * ptr_1 = MK_FP(FP_SEG(&val_a) + 1, FP_OFF(&val_a) - 16);
printf(" val_a = %d -> @%p\n", val_a, (void *)(&val_a));
printf("*ptr_0 = %d -> @%p\n", *ptr_0, (void *)ptr_0);
printf("*ptr_1 = %d -> @%p\n", *ptr_1, (void *)ptr_1);
/* Check what returns the pointers comparison: */
printf("&val_a == ptr_0 ====> %d\n", &val_a == ptr_0);
printf("&val_a == ptr_1 ====> %d\n", &val_a == ptr_1);
printf(" ptr_0 == ptr_1 ====> %d\n", ptr_0 == ptr_1);
printf("val_a = %d\n", val_a);
printf(">> *ptr_0 += 100;\n");
*ptr_0 += 100;
printf("val_a = %d\n", val_a);
printf(">> *ptr_1 += 500;\n");
*ptr_1 += 500;
printf("val_a = %d\n", val_a);
return EXIT_SUCCESS;
}
/*--{--:main.c}--------------------------------------------------*/
Compile it under Borland C 5.0, here is the result:
/*--{++:result}--------------------------------------------------*/
val_a = 123 -> @167A:0FFE
*ptr_0 = 123 -> @167A:0FFE
*ptr_1 = 123 -> @167B:0FEE
&val_a == ptr_0 ====> 1
&val_a == ptr_1 ====> 0
ptr_0 == ptr_1 ====> 0
val_a = 123
>> *ptr_0 += 100;
val_a = 223
>> *ptr_1 += 500;
val_a = 723
/*--{--:result}--------------------------------------------------*/
The syntax you used is problematic. In html, an attribute (ex: style) has a value delimited by double quotes. In that case, the value of the style attribute is a css list of selectors. Try this:
<h2 style="text-align:center; font-family:tahoma">TITLE</h2>
Add an id attribute to a html tag
<ul class="nav nav-tabs">
<li><a href="#aaa" data-toggle="tab" id="tab_aaa">AAA</a></li>
<li><a href="#bbb" data-toggle="tab" id="tab_bbb">BBB</a></li>
<li><a href="#ccc" data-toggle="tab" id="tab_ccc">CCC</a></li>
</ul>
<div class="tab-content" id="tabs">
<div class="tab-pane" id="aaa">...Content...</div>
<div class="tab-pane" id="bbb">...Content...</div>
<div class="tab-pane" id="ccc">...Content...</div>
</div>
Then using JQuery
$("#tab_aaa").tab('show');
I was having trouble with react-native-navigation, I created my own header component, then inserted a image - as logo - on the left before title, then when I was triggering navigate to another screen and then back again, logo was loading again, with a timeout near 1s, my file were local. My solution :
Logo.json
{"file" : "base64 big string"}
App.js
import Logo from '.../Logo.json'
...
<Image source:{{uri:Logo.file}} />
From Hadley Wickham:
My (crappy looking) modification to show using tidyverse / purrr:
As ibram stated, add the manifest thru solution explorer:
This creates a default manifest. Now, edit the manifest.
If you got nothing when inputted fastboot devices
, it meaned you devices fail to enter fastboot model. Make sure that you enter fastboot model via press these three button simultaneously, power key, volume key(both '+' and '-').
Then you can see you devices via fastboot devices
and continue to flash your devices.
note:I entered fastboot model only pressed 'power key' and '-' key before, and present the same problem.
I used postman chrome extension until it became deprecated. Chrome extension also less usable and powerful then native postman application. So, it became not very convenient to use chrome extension. I have found next approach:
Downgrading Node to 0.10.36 should do it per this thread on the node-sass github page: https://github.com/sass/node-sass/issues/490#issuecomment-70388754
If you have NVM you can just:
nvm install 0.10
If you don't, you can find NVM and instructions here: https://www.npmjs.com/package/nvm
No need to remove format detection by using <meta name="format-detection" content="telephone=no">
. Try using phone number in any tag rather then anchor tag and style it accordingly e.g.: span { background:none !important; border:0; padding:0; }
Simply you could change the gradle.properties . i have given the sample below
You defined Base64? If you not defined, occurs this error:
ReferenceError: Base64 is not defined
You can add the --packages parameter with the appropriate jar: to your submission:
bin/spark-submit --packages com.amazonaws:aws-java-sdk-pom:1.10.34,org.apache.hadoop:hadoop-aws:2.6.0 code.py
For starters:
<p align='center'>
<table width='100%'>
<tr>
<td align='center'><form><input type=submit value="click me" style="width:100%"></form></td>
</tr>
</table>
</p>
Note, if the width of the input button is 100%, you wont need the attribute "align='center'" anymore.
This would be the optimal solution:
<p align='center'>
<table width='100%'>
<tr>
<td><form><input type=submit value="click me" style="width:100%"></form></td>
</tr>
</table>
</p>
To convert notebooks to PDF you first need to have nbconvert installed.
pip install nbconvert
# OR
conda install nbconvert
Next, if you aren't using Anaconda or haven't already, you must install pandoc either by following the instructions on their website or, on Linux, as follows:
sudo apt-get install pandoc
After that you need to have XeTex installed on your machine:
You can now navigate to the folder that holds your IPython Notebook and run the following command:
jupyter nbconvert --to pdf MyNotebook.ipynb
for further reference, please check out this link.
If looking for a unique list while grouping multiple columns this could probably help:
df.groupby('a').agg(lambda x: list(set(x))).reset_index()
#At Controller
def branch
@data = Model.all
render json: JSON.pretty_generate(@data.as_json)
end
You should have a look at FindBoost.cmake
script, which handles Boost detection and setting up all Boost variables. It typically resides in /usr/share/cmake-2.6/Modules/
. In it, you will find documentation. For instance:
# These last three variables are available also as environment variables:
#
# BOOST_ROOT or BOOSTROOT The preferred installation prefix for searching for
# Boost. Set this if the module has problems finding
# the proper Boost installation.
#
In contrast to BOOST_ROOT, the variables you are referring to are actually variables that are set by the FindBoost module. Note that you don't have to (and probably also don't want to) edit your CMake project configuration to set BOOST_ROOT. Instead, you should use the environment variable, e.g. calling
# BOOST_ROOT=/usr/local/... ccmake .
C:/Windows/System32
(windows 7, 32 bits). If not, you can download it DLL-files.com and install it under C:/Windows/System32. System.Diagnostics.Process.Start("PATH to exe", "Command Line Arguments");
I have the same issue with windows10, apache 2.2.25, php 5.2 Im trying to add GD to a working PHP.
how I turn around and change between forward and backward slash, plus trailing or not, I get some variant of ;
PHP Warning: PHP Startup: Unable to load dynamic library 'C:/php\php_gd2.dll' - Det g\xe5r inte att hitta den angivna modulen.\r\n in Unknown on line 0
(swedish translated: 'It is not possible to find the module' )
in this perticular case, the php.ini was: extension_dir = "C:/php"
the dll is put in two places C:\php and C:\php\ext
IS it possible that there is and "error" in the error log entry ? I.e. that the .dll IS found (as a file) but not of the right format, or something like that ??
If you want to use JDKs downloaded from Oracle's site, what worked for me (using Mint) is using update-alternatives:
I ran:
sudo update-alternatives --install /usr/bin/java java /home/aqeel/development/jdk/jdk1.6.0_35/bin/java 1
Now you can execute sudo update-alternatives --config java
and choose your java version.
export JAVA_HOME="/home/aqeel/development/jdk/jdk1.6.0_35"
statementNow, I had two JDKs downloaded (let's say the second has been extracted to /home/aqeel/development/jdk/jdk-10.0.1).
How can we change the JAVA_HOME dynamically based on the current java being used?
My solution is not very elegant, I'm pretty sure there are better options out there, but anyway:
To change the JAVA_HOME dynamically based on the chosen java alternative, I added this snippet to the ~/.bashrc:
export JAVA_HOME=$(update-alternatives --query java | grep Value: | awk -F'Value: ' '{print $2}' | awk -F'/bin/java' '{print $1}')
Finally (this is out of the scope) if you have to change the java version constantly, you might want to consider:
Adding an alias to your ~./bash_aliases:
alias change-java="sudo update-alternatives --config java"
(You might have to create the file and maybe uncomment the section related to this in ~/.bashrc)
In case anyone is running in a Spring Boot app, and you want to read the response body of a RestTemplate
(which is why I want to read a stream twice), there is a clean(er) way of doing this.
First of all, you need to use Spring's StreamUtils
to copy the stream to a String:
String text = StreamUtils.copyToString(response.getBody(), Charset.defaultCharset()))
But that's not all. You also need to use a request factory that can buffer the stream for you, like so:
ClientHttpRequestFactory factory = new BufferingClientHttpRequestFactory(new SimpleClientHttpRequestFactory());
RestTemplate restTemplate = new RestTemplate(factory);
Or, if you're using the factory bean, then (this is Kotlin but nevertheless):
@Bean
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
fun createRestTemplate(): RestTemplate = RestTemplateBuilder()
.requestFactory { BufferingClientHttpRequestFactory(SimpleClientHttpRequestFactory()) }
.additionalInterceptors(loggingInterceptor)
.build()
I think NSDecimalNumber will do it:
Example:
NSNumber *theNumber = [NSDecimalNumber decimalNumberWithString:[stringVariable text]]];
NSDecimalNumber is a subclass of NSNumber, so implicit casting allowed.
This one worked in my python script:
print "\t%-5s %-10s %-10s %-10s %-10s %-10s %-20s" % (thread[0],thread[1],thread[2],thread[3],thread[4],thread[5],thread[6])
Found my solution on Apache/2.2.15 (Unix).
And Thanks for answer from @QuantumHive:
First: I finded all
Order allow,deny
Deny from all
instead of
Order allow,deny
Allow from all
and then:
I setted
#
# Control access to UserDir directories. The following is an example
# for a site where these directories are restricted to read-only.
#
#<Directory /var/www/html>
# AllowOverride FileInfo AuthConfig Limit
# Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec
# <Limit GET POST OPTIONS>
# Order allow,deny
# Allow from all
# </Limit>
# <LimitExcept GET POST OPTIONS>
# Order deny,allow
# Deny from all
# </LimitExcept>
#</Directory>
Remove the previous "#" annotation to
#
# Control access to UserDir directories. The following is an example
# for a site where these directories are restricted to read-only.
#
<Directory /var/www/html>
AllowOverride FileInfo AuthConfig Limit
Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec
<Limit GET POST OPTIONS>
Order allow,deny
Allow from all
</Limit>
<LimitExcept GET POST OPTIONS>
Order deny,allow
Deny from all
</LimitExcept>
</Directory>
ps. my WebDir is: /var/www/html
if (obj === undefined)
{
// Create obj
}
If you are doing extensive javascript programming you should get in the habit of using === and !== when you want to make a type specific check.
Also if you are going to be doing a fair amount of javascript, I suggest running code through JSLint http://www.jslint.com it might seem a bit draconian at first, but most of the things JSLint warns you about will eventually come back to bite you.
If you have a fixed div
just absolute position it at 50% from the top and 50% left and negative margin top and left of half the height and width respectively. Adjust to your needs:
div {
position: absolute;
top: 50%;
left: 50%;
width: 500px;
height: 300px;
margin-left: -250px;
margin-top: -150px;
}
You can use this
string x = "ABCGH"
char[] charX = x.ToCharArray();
Array.Sort(charX);
This will sort your string.
You may consider 3rd party tool that called Excel Jetcell .NET component for read/write excel files:
C# sample
// Create New Excel Workbook
ExcelWorkbook Wbook = new ExcelWorkbook();
ExcelCellCollection Cells = Wbook.Worksheets.Add("Sheet1").Cells;
Cells["A1"].Value = "Excel writer example (C#)";
Cells["A1"].Style.Font.Bold = true;
Cells["B1"].Value = "=550 + 5";
// Write Excel XLS file
Wbook.WriteXLS("excel_net.xls");
VB.NET sample
' Create New Excel Workbook
Dim Wbook As ExcelWorkbook = New ExcelWorkbook()
Dim Cells As ExcelCellCollection = Wbook.Worksheets.Add("Sheet1").Cells
Cells("A1").Value = "Excel writer example (C#)"
Cells("A1").Style.Font.Bold = True
Cells("B1").Value = "=550 + 5"
' Write Excel XLS file
Wbook.WriteXLS("excel_net.xls")
Additionally, if you have multiple columns to insert and want to check if they exists or not use the following code
Insert Into [Competitors] (cName, cCity, cState)
Select cName, cCity, cState from
(
select new.* from
(
select distinct cName, cCity, cState
from [Competitors] s, [City] c, [State] s
) new
left join
(
select distinct cName, cCity, cState
from [Competitors] s
) existing
on new.cName = existing.cName and new.City = existing.City and new.State = existing.State
where existing.Name is null or existing.City is null or existing.State is null
)
Try This
SELECT Title from #Movies
SELECT CASE WHEN Title = '' THEN 'No Title' ELSE Title END AS Titile from #Movies
OR
SELECT [Id], [CategoryId], ISNULL(nullif(Title,''),'No data') as Title, [Director], [DateReleased] FROM #Movies
rising_edge is defined as:
FUNCTION rising_edge (SIGNAL s : std_ulogic) RETURN BOOLEAN IS
BEGIN
RETURN (s'EVENT AND (To_X01(s) = '1') AND
(To_X01(s'LAST_VALUE) = '0'));
END;
FUNCTION To_X01 ( s : std_ulogic ) RETURN X01 IS
BEGIN
RETURN (cvt_to_x01(s));
END;
CONSTANT cvt_to_x01 : logic_x01_table := (
'X', -- 'U'
'X', -- 'X'
'0', -- '0'
'1', -- '1'
'X', -- 'Z'
'X', -- 'W'
'0', -- 'L'
'1', -- 'H'
'X' -- '-'
);
If your clock only goes from 0 to 1, and from 1 to 0, then rising_edge will produce identical code. Otherwise, you can interpret the difference.
Personally, my clocks only go from 0 to 1 and vice versa. I find rising_edge(clk)
to be more descriptive than the (clk'event and clk = '1')
variant.
CLOCK_REALTIME
represents the machine's best-guess as to the current wall-clock, time-of-day time. As Ignacio and MarkR say, this means that CLOCK_REALTIME
can jump forwards and backwards as the system time-of-day clock is changed, including by NTP.
CLOCK_MONOTONIC
represents the absolute elapsed wall-clock time since some arbitrary, fixed point in the past. It isn't affected by changes in the system time-of-day clock.
If you want to compute the elapsed time between two events observed on the one machine without an intervening reboot, CLOCK_MONOTONIC
is the best option.
Note that on Linux, CLOCK_MONOTONIC
does not measure time spent in suspend, although by the POSIX definition it should. You can use the Linux-specific CLOCK_BOOTTIME
for a monotonic clock that keeps running during suspend.
In case you cannot change the declaration for whatever reason, you can do:
char ch = 212;
printf("%d", (unsigned char) ch);
Try, the following code..
@Override
public String toString() {
return this.name();
}
If I understand what you're asking, this should do the trick:
// the more standards compliant browsers (mozilla/netscape/opera/IE7) use
// window.innerWidth and window.innerHeight
var windowHeight;
if (typeof window.innerWidth != 'undefined')
{
windowHeight = window.innerHeight;
}
// IE6 in standards compliant mode (i.e. with a valid doctype as the first
// line in the document)
else if (typeof document.documentElement != 'undefined'
&& typeof document.documentElement.clientWidth != 'undefined'
&& document.documentElement.clientWidth != 0)
{
windowHeight = document.documentElement.clientHeight;
}
// older versions of IE
else
{
windowHeight = document.getElementsByTagName('body')[0].clientHeight;
}
document.getElementById("yourDiv").height = windowHeight - 300 + "px";
This worked for me may times:
ssh -x remoteServer "cd yourRemoteDir; ./yourRemoteScript.sh </dev/null >/dev/null 2>&1 & "
Maybe more simple;
var top = window.pageYOffset || document.documentElement.scrollTop,
left = window.pageXOffset || document.documentElement.scrollLeft;
Credits: so.dom.js#L492
Added streaming support based on the answer of @dunes:
import re
from json import JSONDecoder, JSONDecodeError
NOT_WHITESPACE = re.compile(r"[^\s]")
def stream_json(file_obj, buf_size=1024, decoder=JSONDecoder()):
buf = ""
ex = None
while True:
block = file_obj.read(buf_size)
if not block:
break
buf += block
pos = 0
while True:
match = NOT_WHITESPACE.search(buf, pos)
if not match:
break
pos = match.start()
try:
obj, pos = decoder.raw_decode(buf, pos)
except JSONDecodeError as e:
ex = e
break
else:
ex = None
yield obj
buf = buf[pos:]
if ex is not None:
raise ex
Try this code:
HTML:
<div id="demo"></div>
JavaScript code:
<script>
(function(){
var points = [40, 100, 1, 5, 25, 10];
document.getElementById("demo").innerHTML = points;
points.sort(function(a, b){return a-b});
document.getElementById("demo").innerHTML = points;
})();
</script>
You can also try this one as well with data-myTag
<select id="location">
<option value="a" data-myTag="123">My option</option>
<option value="b" data-myTag="456">My other option</option>
</select>
<input type="hidden" id="setMyTag" />
<script>
$(function() {
$("#location").change(function(){
var myTag = $('option:selected', this).data("myTag");
$('#setMyTag').val(myTag);
});
});
</script>
Filter the version number.
java -version 2>&1 | head -n 1 | awk -F '"' '{print $2}'
It is the simplest one I could come up with, so wanted to share here,
#include<iostream.h>
#include<conio.h>
void main()
{
//clear the screen.
clrscr();
//declare variable type float
float cel, fah;
//Input the Temperature in given unit save them in ‘cel’
cout<<”Enter the Temperature in Celsius”<<endl;
cin>>cel;
//convert and save it in ‘fah’
fah=1.8*cel+32.0;
//show the output ‘fah’
cout<<”Temperature in Fahrenheit is “<<fah;
//get character
getch();
}
Source: Celsius to Fahrenheit
Change your custom overflow icon of Actionbar in styles.xml
<resources>
<!-- Base application theme. -->
<style name=“MyTheme" parent="@android:style/Theme.Holo">
<!-- Pointer to Overflow style DONT forget! -->
<item name="android:actionOverflowButtonStyle">@style/MyOverFlow</item>
</style>
<!-- Styles -->
<style name="MyOverFlow" parent="@android:style/Widget.Holo.ActionButton.Overflow">
<item name="android:src">@drawable/ic_your_action_overflow</item>
</style>
</resources>
Put custom theme "MyTheme" in application tag of AndroidManifest.xml
<application
android:name="com.example.android.MainApp"
android:theme="@style/AppTheme">
</application>
Have fun.@.@
If you download the latest version of Adobe Acrobat Reader, it will tell you if your pdf is PDF/A compliant. Just open the PDF file and a big blue marking should appear.
OpenOffice supports PDF/A. For some reason "PDF/A-1" is called
"SelectPdfVersion"internally in OpenOffice. Just add 1 to that value and your output should be PDF/A.
The different values can be
0 = PDFXNONE
1 = PDFX1A2001
2 = PDFX32002
3 = PDFA1A
4 = PDFA1B
You set
FilterDatato be a
HashMap('SelectPdfVersion',1) //1 for PDFX1A2001
Why dont you go with the XMPP implementation. right now there are so many public servers available including gtalk, jabber, citadel etc. For Android there is one SDK is also available named as SMACK. This we cant say a push notification but using the XMPP you can keep a connection open between client and server which will allow a two way communication. Means Android client and server both can communicate to each other. At present this will fulfill the need of Push in android. I have implemented a sample code and it really works great
Taken from http://www.dotnetspider.com/resources/189-AutoPostBack-What-How-works.aspx:
Autopostback
is the mechanism by which the page will be posted back to the server automatically based on some events in the web controls. In some of the web controls, the property called auto post back, if set to true, will send the request to the server when an event happens in the control.Whenever we set the autopostback attribute to true on any of the controls, the .NET framework will automatically insert a few lines of code into the HTML generated to implement this functionality.
- A JavaScript method with name __doPostBack (eventtarget, eventargument)
- Two hidden variables with name __EVENTTARGET and __EVENTARGUMENT
- OnChange JavaScript event to the control
In the most simple terms extends is used to inherit from a class and implements is used to apply an interface in your class
extends:
public class Bicycle {
//properties and methods
}
public class MountainBike extends Bicycle {
//new properties and methods
}
implements:
public interface Relatable {
//stuff you want to put
}
public class RectanglePlus implements Relatable {
//your class code
}
if you still have confusion read this: https://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html https://docs.oracle.com/javase/tutorial/java/IandI/usinginterface.html
this is the actual regex only match:
/[-!$%^&*()_+|~=`{}[:;<>?,.@#\]]/g
<div ng-controller="ExampleController">
<form name="myForm">
<label for="repeatSelect"> Repeat select: </label>
<select name="repeatSelect" id="repeatSelect" ng-model="data.model">
<option ng-repeat="option in data.availableOptions" value="{{option.id}}">{{option.name}}</option>
</select>
</form>
<hr>
<tt>model = {{data.model}}</tt><br/>
</div>
AngularJS:
angular.module('ngrepeatSelect', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.data = {
model: null,
availableOptions: [
{id: '1', name: 'Option A'},
{id: '2', name: 'Option B'},
{id: '3', name: 'Option C'}
]
};
}]);
taken from AngularJS docs
Just had the same issue, for those having the same one it may be that you put the library on the modulepath rather than the classpath while adding it to your project
I had the same error because there was one more project under svn in workspace but with another name. So I've removed it.
Here is a different approach using mix-blend-mode: difference
, that will actually invert whatever the background is, not just a single colour:
div {_x000D_
background-image: linear-gradient(to right, red, yellow, green, cyan, blue, violet);_x000D_
}_x000D_
p {_x000D_
color: white;_x000D_
mix-blend-mode: difference;_x000D_
}
_x000D_
<div>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscit elit, sed do</p>_x000D_
</div>
_x000D_
I think you want something like
var count = context.MyTable.Count(t => t.MyContainer.ID == '1');
(edited to reflect comments)
EDIT
Updated for Swift 4.2
let appVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String
EDIT
As pointed out by @azdev on the new version of Xcode you will get a compile error for trying my previous solution, to solve this just edit it as suggested to unwrap the bundle dictionary using a !
let nsObject: AnyObject? = Bundle.main.infoDictionary!["CFBundleShortVersionString"]
End Edit
Just use the same logic than in Objective-C but with some small changes
//First get the nsObject by defining as an optional anyObject
let nsObject: AnyObject? = NSBundle.mainBundle().infoDictionary["CFBundleShortVersionString"]
//Then just cast the object as a String, but be careful, you may want to double check for nil
let version = nsObject as! String
I hope this helps you out.
David
last record :
SELECT * FROM `aboutus` order by id desc limit 1
first record :
SELECT * FROM `aboutus` order by id asc limit 1
This was the fix for me when trying to install Laravel on a fresh WSL installation:
sudo apt-get install php7.2-gd
sudo apt-get install php7.2-intl
sudo apt-get install php7.2-xsl
sudo apt-get install php7.2-zip
The solution is:
Update-Database –TargetMigration 201609261919239_yourLastMigrationSucess
A handy post explaining several mis-understandings about this:
Don't Call The Destructor explicitly
This covers several misconceptions about how the destructor works. Calling it explicitly will not actually destroy your variable, according to the PHP5 doc:
PHP 5 introduces a destructor concept similar to that of other object-oriented languages, such as C++. The destructor method will be called as soon as there are no other references to a particular object, or in any order during the shutdown sequence.
The post above does state that setting the variable to null can work in some cases, as long as nothing else is pointing to the allocated memory.
Solution for Eclipse IDE
In my case I fixed it by correcting one of these two files that may be corrupt: .classpath or .project.
To repair any of the corrupted files, you can copy from another project that has both the .project file or .classpath file in question and is error-free. But be sure not to add additional settings that will not be used.
Swift:
You could use an extension like this:
extension UIScrollView {
func scrollsToBottom(animated: Bool) {
let bottomOffset = CGPoint(x: 0, y: contentSize.height - bounds.size.height)
setContentOffset(bottomOffset, animated: animated)
}
}
Use:
scrollView.scrollsToBottom(animated: true)
Ecu, if you do myObj.a
, then it looks for the property named a of myObj.
If you do myObj[a] =b
then it looks for the a.valueOf()
property of myObj.
Problem Cause
In mac os image rendering back end of matplotlib (what-is-a-backend to render using the API of Cocoa by default). There are Qt4Agg and GTKAgg and as a back-end is not the default. Set the back end of macosx that is differ compare with other windows or linux os.
Solution
~/.matplotlib
. ~/.matplotlib/matplotlibrc
there and add the following code: backend: TkAgg
From this link you can try different diagrams.
You can do it pretty fast without creating extra arrays, so this will work even for very large arrays:
dict(izip(*([iter(a)]*2)))
If you have a generator a
, even better:
dict(izip(*([a]*2)))
Here's the rundown:
iter(h) #create an iterator from the array, no copies here
[]*2 #creates an array with two copies of the same iterator, the trick
izip(*()) #consumes the two iterators creating a tuple
dict() #puts the tuples into key,value of the dictionary
Let me seperate up everything and solve approach each problem in isolation:
Authentication
For authentication, baseauth has the advantage that it is a mature solution on the protocol level. This means a lot of "might crop up later" problems are already solved for you. For example, with BaseAuth, user agents know the password is a password so they don't cache it.
Auth server load
If you dispense a token to the user instead of caching the authentication on your server, you are still doing the same thing: Caching authentication information. The only difference is that you are turning the responsibility for the caching to the user. This seems like unnecessary labor for the user with no gains, so I recommend to handle this transparently on your server as you suggested.
Transmission Security
If can use an SSL connection, that's all there is to it, the connection is secure*. To prevent accidental multiple execution, you can filter multiple urls or ask users to include a random component ("nonce") in the URL.
url = username:[email protected]/api/call/nonce
If that is not possible, and the transmitted information is not secret, I recommend securing the request with a hash, as you suggested in the token approach. Since the hash provides the security, you could instruct your users to provide the hash as the baseauth password. For improved robustness, I recommend using a random string instead of the timestamp as a "nonce" to prevent replay attacks (two legit requests could be made during the same second). Instead of providing seperate "shared secret" and "api key" fields, you can simply use the api key as shared secret, and then use a salt that doesn't change to prevent rainbow table attacks. The username field seems like a good place to put the nonce too, since it is part of the auth. So now you have a clean call like this:
nonce = generate_secure_password(length: 16);
one_time_key = nonce + '-' + sha1(nonce+salt+shared_key);
url = username:[email protected]/api/call
It is true that this is a bit laborious. This is because you aren't using a protocol level solution (like SSL). So it might be a good idea to provide some kind of SDK to users so at least they don't have to go through it themselves. If you need to do it this way, I find the security level appropriate (just-right-kill).
Secure secret storage
It depends who you are trying to thwart. If you are preventing people with access to the user's phone from using your REST service in the user's name, then it would be a good idea to find some kind of keyring API on the target OS and have the SDK (or the implementor) store the key there. If that's not possible, you can at least make it a bit harder to get the secret by encrypting it, and storing the encrypted data and the encryption key in seperate places.
If you are trying to keep other software vendors from getting your API key to prevent the development of alternate clients, only the encrypt-and-store-seperately approach almost works. This is whitebox crypto, and to date, no one has come up with a truly secure solution to problems of this class. The least you can do is still issue a single key for each user so you can ban abused keys.
(*) EDIT: SSL connections should no longer be considered secure without taking additional steps to verify them.
If you simply want to add it without creating a new class try this:
// WPF
<ComboBox Name="language" Loaded="language_Loaded" />
// C# code
private void language_Loaded(object sender, RoutedEventArgs e)
{
List<String> language= new List<string>();
language.Add("English");
language.Add("Spanish");
language.Add("ect");
this.chartReviewComboxBox.ItemsSource = language;
}
I suggest an xml file with all your languages that you will support that way you do not have to be dependent on c# I would definitly create a class for languge like the above programmer suggest.
Oli has a solution that will work for me. For the record, the page inside my iFrame is rendered by javascript, so I'll need an infinitesimal delay before reporting back the offsetHeight. It looks like something along these lines:
$(document).ready(function(){
setTimeout(setHeight);
});
function setHeight() {
alert(document['body'].offsetHeight);
}
You can install the dateutil library. Its parse
function can figure out what format a string is in without having to specify the format like you do with datetime.strptime
.
from dateutil.parser import parse
dt = parse('Mon Feb 15 2010')
print(dt)
# datetime.datetime(2010, 2, 15, 0, 0)
print(dt.strftime('%d/%m/%Y'))
# 15/02/2010
.switch
{
width: 50px;
height: 30px;
position: relative;
display:inline-block;
}
.switch input
{
display: none;
}
.slider
{
position: absolute;
top: 0;
bottom: 0;
right: 0;
left: 0;
cursor: pointer;
background-color: gray;
border-radius: 30px;
}
.slider:before
{
position: absolute;
background-color: #fff;
height: 20px;
width: 20px;
content: "";
left: 5px;
bottom: 5px;
border-radius: 50%;
transition: ease-in-out .5s;
}
.slider:after
{
content: "Off";
color: white;
display: block;
position: absolute;
transform: translate(-50%,-50%);
top: 50%;
left: 70%;
transition: all .5s;
font-size: 10px;
font-family: Verdana,sans-serif;
}
input:checked + .slider:after
{
transition: all .5s;
left: 30%;
content: "On"
}
input:checked + .slider
{
background-color: blue;
}
input:checked + .slider:before
{
transform: translateX(20px);
}
**The HTML CODE**
<label class="switch">
<input type="checkbox"/>
<div class="slider">
</div>
</label>
If You want to add long text like activate or Deactivate
just make few changes
.switch
{
width:90px
}
.slider:after
{
left: 60%; //as you want in percenatge
}
input:checked + .slider:after
{
left:40%; //exactly opposite of .slider:after
}
and last
input:checked + .slider:before
{
transform: translateX(60px); //as per your choice but 60px is perfect
}
content as per your choice where you have witten "On" and "Off"
In your css add folllowing
[ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {
display: none !important;
}
And then in you code you can add ng-cloak directive. For example,
<div ng-cloak>
Welcome {{data.name}}
</div>
Thats it!
as you can see on the answer to this question: Conversion of a varchar data type to a datetime data type resulted in an out-of-range value
-- set the dateformat for the current session
set dateformat dmy
-- The conversion of a varchar data type
-- to a datetime data type resulted in an out-of-range value.
select cast('2017-08-13 16:31:31' as datetime)
-- get the current session date_format
select date_format
from sys.dm_exec_sessions
where session_id = @@spid
-- set the dateformat for the current session
set dateformat ymd
-- this should work
select cast('2017-08-13 16:31:31' as datetime)
Just in case this helps someone, I was getting this error because I completely missed the stated fact that the scope prefix must not be used when calling a local scope. So if you defined a local scope in your model like this:
public function scopeRecentFirst($query)
{
return $query->orderBy('updated_at', 'desc');
}
You should call it like:
$CurrentUsers = \App\Models\Users::recentFirst()->get();
Note that the prefix scope
is not present in the call.
.phtml files tell the webserver that those are html files with dynamic content which is generated by the server... just like .php files in a browser behave. So, in productive usage you should experience no difference from .phtml to .php files.
Thanks to your answer @RDC.
The following codes works with Swift 3
// MARK: - UICollectionViewDataSource protocol
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
//prepare your cell here..
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as! MyCell
cell.myLabel.text = "my text"
//Add background view for normal cell
let backgroundView: UIView = UIView(frame: cell.bounds)
backgroundView.backgroundColor = UIColor.lightGray
cell.backgroundView = backgroundView
//Add background view for selected cell
let selectedBGView: UIView = UIView(frame: cell.bounds)
selectedBGView.backgroundColor = UIColor.green
cell.selectedBackgroundView = selectedBGView
return cell
}
// MARK: - UICollectionViewDelegate protocol
func collectionView(_ collectionView: UICollectionView, shouldHighlightItemAt indexPath: IndexPath) -> Bool {
return true
}
func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
return true
}
There's a simple way to do this if you only need to support modern browsers: on your submit button, add a formaction="/alternate/submit/url"
attribute like so:
<form>
[fields]
<input type="submit" value="Submit to a" formaction="/submit/a">
<input type="submit" value="submit to b" formaction="/submit/b">
</form>
It also works on <button>
tags.
The gotcha is that old versions of IE (<10) and the Android Browser (<4.0) do not support it. So, if you need to support older browsers, then the existing JS answers will probably work better for you.
More info: http://www.wufoo.com/html5/attributes/13-formaction.html
The following will work. Please note [0]
and scrollHeight
$("#myDiv").animate({ scrollTop: $("#myDiv")[0].scrollHeight }, 1000);
Use pipelist.exe from Sysinternals.
I couldn't leave this question here with out a single statement using the modulo operator.
def rot13(s):
return ''.join([chr(x.islower() and ((ord(x) - 84) % 26) + 97
or x.isupper() and ((ord(x) - 52) % 26) + 65
or ord(x))
for x in s])
This is not pythonic nor good practice, but it works!
>> rot13("Hello World!")
Uryyb Jbeyq!
The default name for a configuration file is [yourexe].exe.config. So notepad.exe will have a configuration file named notepad.exe.config, in the same folder as the program. This is a general configuration file for all aspects of the CLR and Framework, but it can contain your own settings under an <appSettings>
node.
The <appSettings>
element creates a collection of name-value pairs which can be accessed as System.Configuration.ConfigurationSettings.AppSettings
. There is no way to save changes back to the configuration file, however.
It is also possible to add your own custom elements to a configuration file - for example, to define a structured setting - by creating a class that implements IConfigurationSectionHandler
and adding it to the <configSections>
element of the configuration file. You can then access it by calling ConfigurationSettings.GetConfig
.
.NET 2.0 adds a new class, System.Configuration.ConfigurationManager
, which supports multiple files, with per-user overrides of per-system data. It also supports saving modified configurations back to settings files.
Visual Studio creates a file called App.config
, which it copies to the EXE folder, with the correct name, when the project is built.
XStream!
Updated: I added unmarshal part as requested in comments..
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import java.util.AbstractMap;
import java.util.HashMap;
import java.util.Map;
public class Test {
public static void main(String[] args) {
Map<String,String> map = new HashMap<String,String>();
map.put("name","chris");
map.put("island","faranga");
XStream magicApi = new XStream();
magicApi.registerConverter(new MapEntryConverter());
magicApi.alias("root", Map.class);
String xml = magicApi.toXML(map);
System.out.println("Result of tweaked XStream toXml()");
System.out.println(xml);
Map<String, String> extractedMap = (Map<String, String>) magicApi.fromXML(xml);
assert extractedMap.get("name").equals("chris");
assert extractedMap.get("island").equals("faranga");
}
public static class MapEntryConverter implements Converter {
public boolean canConvert(Class clazz) {
return AbstractMap.class.isAssignableFrom(clazz);
}
public void marshal(Object value, HierarchicalStreamWriter writer, MarshallingContext context) {
AbstractMap map = (AbstractMap) value;
for (Object obj : map.entrySet()) {
Map.Entry entry = (Map.Entry) obj;
writer.startNode(entry.getKey().toString());
Object val = entry.getValue();
if ( null != val ) {
writer.setValue(val.toString());
}
writer.endNode();
}
}
public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
Map<String, String> map = new HashMap<String, String>();
while(reader.hasMoreChildren()) {
reader.moveDown();
String key = reader.getNodeName(); // nodeName aka element's name
String value = reader.getValue();
map.put(key, value);
reader.moveUp();
}
return map;
}
}
}
Always use std::copy
because memcpy
is limited to only C-style POD structures, and the compiler will likely replace calls to std::copy
with memcpy
if the targets are in fact POD.
Plus, std::copy
can be used with many iterator types, not just pointers. std::copy
is more flexible for no performance loss and is the clear winner.
Since adjacent string literals are automatically joint into a single string, you can just use the implied line continuation inside parentheses as recommended by PEP 8:
print("Why, hello there wonderful "
"stackoverflow people!")
You have to mention the width of the h1 tag..
your css will be like this
h1 {
text-align: center;
background-color: green;
width: 600px;
}
The formula above didn't work for me, but I used this without any issue. Pass your current location to the function, and loop through an array of markers to find the closest:
function find_closest_marker( lat1, lon1 ) {
var pi = Math.PI;
var R = 6371; //equatorial radius
var distances = [];
var closest = -1;
for( i=0;i<markers.length; i++ ) {
var lat2 = markers[i].position.lat();
var lon2 = markers[i].position.lng();
var chLat = lat2-lat1;
var chLon = lon2-lon1;
var dLat = chLat*(pi/180);
var dLon = chLon*(pi/180);
var rLat1 = lat1*(pi/180);
var rLat2 = lat2*(pi/180);
var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(rLat1) * Math.cos(rLat2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c;
distances[i] = d;
if ( closest == -1 || d < distances[closest] ) {
closest = i;
}
}
// (debug) The closest marker is:
console.log(markers[closest]);
}
You can get all keys in the Request.Form and then compare and get your desired values.
Your method body will look like this: -
List<int> listValues = new List<int>();
foreach (string key in Request.Form.AllKeys)
{
if (key.StartsWith("List"))
{
listValues.Add(Convert.ToInt32(Request.Form[key]));
}
}
To skip .
& ..
, you can use Dir::each_child
.
Dir.each_child('/path/to/dir') do |filename|
puts filename
end
Dir::children
returns an array of the filenames.
Another functional approach which is maybe a little easier to look at than an anonymous function if you go that route is using functools.partial
to utilize the two-parameter operator.mul
with a fixed multiple
>>> from functools import partial
>>> from operator import mul
>>> double = partial(mul, 2)
>>> list(map(double, [1, 2, 3]))
[2, 4, 6]
:datetime (8 bytes)
:timestamp (4 bytes)
In my case I changed the datetime field in the SQL database to not allow null. SqlDataReader then allowed me to cast the value directly to a DateTime.
Here's your solution: JsFiddle
Basically, place your button into a div with centred text:
<div class="wrapper">
<button class="button">Button</button>
</div>
With the following styles:
.wrapper {
text-align: center;
}
.button {
position: absolute;
top: 50%;
}
There are many ways to skin a cat, and this is just one.
I just needed to do this, but thought Steven's solution would be slow. This should hopefully use graphics HW. Create a category on UIImage:
- (UIImage *)imageByApplyingAlpha:(CGFloat) alpha {
UIGraphicsBeginImageContextWithOptions(self.size, NO, 0.0f);
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGRect area = CGRectMake(0, 0, self.size.width, self.size.height);
CGContextScaleCTM(ctx, 1, -1);
CGContextTranslateCTM(ctx, 0, -area.size.height);
CGContextSetBlendMode(ctx, kCGBlendModeMultiply);
CGContextSetAlpha(ctx, alpha);
CGContextDrawImage(ctx, area, self.CGImage);
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
You can stop the image from overlapping it's edges by clipping the image and applying a wrapper element which sets the blur effect to 0 pixels. This is how it looks like:
HTML
<div id="wrapper">
<div id="image"></div>
</div>
CSS
#wrapper {
width: 1024px;
height: 768px;
border: 1px solid black;
// 'blur(0px)' will prevent the wrapped image
// from overlapping the border
-webkit-filter: blur(0px);
-moz-filter: blur(0px);
-ms-filter: blur(0px);
filter: blur(0px);
}
#wrapper #image {
width: 1024px;
height: 768px;
background-image: url("../images/cats.jpg");
background-size: cover;
-webkit-filter: blur(10px);
-moz-filter: blur(10px);
-ms-filter: blur(10px);
filter: blur(10px);
// Position 'absolute' is needed for clipping
position: absolute;
clip: rect(0px, 1024px, 768px, 0px);
}
You can use Visual Studio - that's paid.
You can use https://www.advancedinstaller.com/ - that has a free edition.
You can use http://nsis.sourceforge.net/Main_Page - for example Winamp uses this installer - and is very configurable and is Open Source.
You can actually try this yourself, that should help you get a feel for how this works.
Open a two windows (tabs) in management studio, each of them will have it's own connection to sql.
Now you can begin a transaction in one window, do some stuff like insert/update/delete, but not yet commit. then in the other window you can see how the database looks from outside the transaction. Depending on the isolation level, the table may be locked until the first window is committed, or you might (not) see what the other transaction has done so far, etc.
Play around with the different isolation levels and no lock hint to see how they affect the results.
Also see what happens when you throw an error in the transaction.
It's very important to understand how all this stuff works or you will be stumped by what sql does, many a time.
Have fun! GJ.
Given
volumes:
- /dir/on/host:/var/www/html
if /dir/on/host
doesn't exist, it is created on the host and the empty content is mounted in the container at /var/www/html
. Whatever content you had before in /var/www/html
inside the container is inaccessible, until you unmount the volume; the new mount is hiding the old content.
you have to be careful because reseved words are not only for table names, also you have to check column names, my mistake was that one of my columns was named "user". If you are using PostgreSQL the correct dialect is: org.hibernate.dialect.PostgreSQLDialect
cheers.
The closest I can get to the answer is by adding an extension method into a System.Type
object. Not pretty, but still interesting.
public static class Foo
{
public static void Bar()
{
var now = DateTime.Now;
var tomorrow = typeof(DateTime).Tomorrow();
}
public static DateTime Tomorrow(this System.Type type)
{
if (type == typeof(DateTime)) {
return DateTime.Now.AddDays(1);
} else {
throw new InvalidOperationException();
}
}
}
Otherwise, IMO Andrew and ShuggyCoUk has a better implementation.
I use the way shown below. It submits everything like files.
$(document).on("submit", "form", function(event)
{
event.preventDefault();
var url = $(this).attr("action");
$.ajax({
url: url,
type: 'POST',
dataType: "JSON",
data: new FormData(this),
processData: false,
contentType: false,
success: function (data, status)
{
},
error: function (xhr, desc, err)
{
console.log("error");
}
});
});
$ g++ 1st.cpp -o 1st
$ ./1st
if you found any error then first install g++ using code as below
$ sudo apt-get install g++
then install g++ and use above run code
You can observe softkeyboard's hide by using activity's decorView.
public final class SoftKeyboardUtil {
public static final String TAG = "SoftKeyboardUtil";
public static void observeSoftKeyBoard(Activity activity , final OnSoftKeyBoardHideListener listener){
final View decorView = activity.getWindow().getDecorView();
decorView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
Rect rect = new Rect();
decorView.getWindowVisibleDisplayFrame(rect);
int displayHight = rect.bottom - rect.top;
int hight = decorView.getHeight();
boolean hide = (double)displayHight / hight > 0.8 ;
if(Log.isLoggable(TAG, Log.DEBUG)){
Log.d(TAG ,"DecorView display hight = "+displayHight);
Log.d(TAG ,"DecorView hight = "+ hight);
Log.d(TAG, "softkeyboard visible = " + !hide);
}
listener.onSoftKeyBoardVisible(!hide);
}
});
}
public interface OnSoftKeyBoardHideListener{
void onSoftKeyBoardVisible(boolean visible);
}
}
Try something like this:
$(function(){
$('input[type="radio"]').click(function(){
if ($(this).is(':checked'))
{
alert($(this).val());
}
});
});
If you give your radio buttons a class then you can replace the code $('input[type="radio"]')
with $('.someclass')
.
Draco,
You can do it like this:
$("#datePickerId").datepicker(
{ dateFormat: 'DD, d MM yy',
minDate: new Date(2009, 10 - 1, 25), // it will set minDate from 25 October 2009
showOn: 'button',
buttonImage: '../../images/calendar.gif',
buttonImageOnly: true,
hideIfNoPrevNext: true
}
);
remember to write -1 after month (ex. for june is -> 6 -1)
To add to @BrianBeech's answer, this is even more trimmed down in java 8:
jdbcTemplate.query("select string1,string2 from table where x=1", (ResultSet rs) -> {
HashMap<String,String> results = new HashMap<>();
while (rs.next()) {
results.put(rs.getString("string1"), rs.getString("string2"));
}
return results;
});
If you are mainly interested in implementing logic to the setter only:
import { Component, Input, OnChanges, SimpleChanges } from '@angular/core';
// [...]
export class MyClass implements OnChanges {
@Input() allowDay: boolean;
ngOnChanges(changes: SimpleChanges): void {
if(changes['allowDay']) {
this.updatePeriodTypes();
}
}
}
The import of SimpleChanges
is not needed if it doesn't matter which input property was changed or if you have only one input property.
otherwise:
private _allowDay: boolean;
@Input() set allowDay(value: boolean) {
this._allowDay = value;
this.updatePeriodTypes();
}
get allowDay(): boolean {
// other logic
return this._allowDay;
}
I believe that you can omit updating the "non-desired" columns by adjusting the other answers as follows:
update table set
columnx = (case when condition1 then 25 end),
columny = (case when condition2 then 25 end)`
As I understand it, this will update only when the condition is met.
After reading all the comments, this is the most efficient:
Update table set ColumnX = 25 where Condition1
Update table set ColumnY = 25 where Condition1`
Sample Table:
CREATE TABLE [dbo].[tblTest](
[ColX] [int] NULL,
[ColY] [int] NULL,
[ColConditional] [bit] NULL,
[id] [int] IDENTITY(1,1) NOT NULL
) ON [PRIMARY]
Sample Data:
Insert into tblTest (ColX, ColY, ColConditional) values (null, null, 0)
Insert into tblTest (ColX, ColY, ColConditional) values (null, null, 0)
Insert into tblTest (ColX, ColY, ColConditional) values (null, null, 1)
Insert into tblTest (ColX, ColY, ColConditional) values (null, null, 1)
Insert into tblTest (ColX, ColY, ColConditional) values (1, null, null)
Insert into tblTest (ColX, ColY, ColConditional) values (2, null, null)
Insert into tblTest (ColX, ColY, ColConditional) values (null, 1, null)
Insert into tblTest (ColX, ColY, ColConditional) values (null, 2, null)
Now I assume you can write a conditional that handles nulls. For my example, I am assuming you have written such a conditional that evaluates to True, False or Null. If you need help with this, let me know and I will do my best.
Now running these two lines of code does infact change X to 25 if and only if ColConditional is True(1) and Y to 25 if and only if ColConditional is False(0)
Update tblTest set ColX = 25 where ColConditional = 1
Update tblTest set ColY = 25 where ColConditional = 0
P.S. The null case was never mentioned in the original question or any updates to the question, but as you can see, this very simple answer handles them anyway.
Just use the format function
format(6, "08b")
The general form is
format(<the_integer>, "<0><width_of_string><format_specifier>")
Personally, I prefer
return "ABCDEFGHIJKLMNOPQRSTUVWXYZ".substring(i, i+1);
which shares the backing char[]
. Alternately, I think the next-most-readable approach is
return Character.toString((char) (i + 'A'));
which doesn't depend on remembering ASCII tables. It doesn't do validation, but if you want to, I'd prefer to write
char c = (char) (i + 'A');
return Character.isUpperCase(c) ? Character.toString(c) : null;
just to make it obvious that you're checking that it's an alphabetic character.
As of bootstrap 4, the answer is to simply set navbar-dark in the nav element, which will set the text and links to a light theme .
<nav class="navbar navbar-dark">
MS Expression Encoder can do mp4/h.264. not sure about ogg though.
The accepted answer is good, but if you are using it to get values from a textView in android, it would be good to check if the string is empty. If the string is empty it would throw an exception.
private String capitizeString(String name){
String captilizedString="";
if(!name.trim().equals("")){
captilizedString = name.substring(0,1).toUpperCase() + name.substring(1);
}
return captilizedString;
}
You don't need to even have the count in the returned columns if you don't need to know the actual number of duplicates. e.g.
SELECT column_name
FROM table
GROUP BY column_name
HAVING COUNT(*) > 1
In Selenium to get the URL of the active tab try,
from selenium import webdriver
driver = webdriver.Firefox()
print driver.current_url # This will print the URL of the Active link
driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + Keys.TAB)
print driver.current_url
I am here just providing a pseudo code for you.
You can put this in a loop and create your own flow.
I new to Stackoverflow so still learning how to write proper answers.
list.Where(m => m.application == "applicationName" &&
m.users.Any(u => u.surname=="surname"));
if you want to filter users as TimSchmelter commented, you can use
list.Where(m => m.application == "applicationName")
.Select(m => new Model
{
application = m.application,
users = m.users.Where(u => u.surname=="surname").ToList()
});
It may be that the Windows Credential Manager is holding onto credentials for the network share.
Load up Credential Manager (the easiest way is perhaps just to Search for that in the Start Menu), see if there are any Windows Credentials for your network share, and try deleting/updating them.
?+?+?/?/?/? will let you navigate split panes in the direction of the arrow, i.e. when using ?+D to split panes vertically, ?+?+? and ?+?+? will let you switch between the panes.
Append extra an [
and ]
to the beginning and end of the string. This will make it an array. Then use eval()
or some safe JSON serializer to serialize the string and make it a real JavaScript datatype.
You should use https://github.com/douglascrockford/JSON-js instead of eval()
. eval is only if you're doing some quick debugging/testing.
This solved my problem. You should select Properties, Right-Click, Source Control and Get Specific Version.
I'm using rather specified charset (ISO-8859-2) because not every mail system (for example: http://10minutemail.com) can read UTF-8 mails. If you need this:
function utf8_to_latin2($str)
{
return iconv ( 'utf-8', 'ISO-8859-2' , $str );
}
function my_mail($to,$s,$text,$form, $reply)
{
mail($to,utf8_to_latin2($s),utf8_to_latin2($text),
"From: $form\r\n".
"Reply-To: $reply\r\n".
"X-Mailer: PHP/" . phpversion());
}
I have made another mailer function, because apple device could not read well the previous version.
function utf8mail($to,$s,$body,$from_name="x",$from_a = "[email protected]", $reply="[email protected]")
{
$s= "=?utf-8?b?".base64_encode($s)."?=";
$headers = "MIME-Version: 1.0\r\n";
$headers.= "From: =?utf-8?b?".base64_encode($from_name)."?= <".$from_a.">\r\n";
$headers.= "Content-Type: text/plain;charset=utf-8\r\n";
$headers.= "Reply-To: $reply\r\n";
$headers.= "X-Mailer: PHP/" . phpversion();
mail($to, $s, $body, $headers);
}
I'm not sure, what you mean as the 'mobile width'. But in each case, the CSS @media
can be used for hiding elements in the screen width basis. See some example:
<div id="my-content"></div>
...and:
@media screen and (min-width: 0px) and (max-width: 400px) {
#my-content { display: block; } /* show it on small screens */
}
@media screen and (min-width: 401px) and (max-width: 1024px) {
#my-content { display: none; } /* hide it elsewhere */
}
Some truly mobile detection is kind of hard programming and rather difficult. Eventually see the: http://detectmobilebrowsers.com/ or other similar sources.
@GetMapping("/downloadfile/{productId}/{fileName}")
public ResponseEntity<Resource> downloadFile(@PathVariable(value = "productId") String productId,
@PathVariable String fileName, HttpServletRequest request) {
// Load file as Resource
Resource resource;
String fileBasePath = "C:\\Users\\v_fzhang\\mobileid\\src\\main\\resources\\data\\Filesdown\\" + productId
+ "\\";
Path path = Paths.get(fileBasePath + fileName);
try {
resource = new UrlResource(path.toUri());
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
}
// Try to determine file's content type
String contentType = null;
try {
contentType = request.getServletContext().getMimeType(resource.getFile().getAbsolutePath());
} catch (IOException ex) {
System.out.println("Could not determine file type.");
}
// Fallback to the default content type if type could not be determined
if (contentType == null) {
contentType = "application/octet-stream";
}
return ResponseEntity.ok().contentType(MediaType.parseMediaType(contentType))
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
.body(resource);
}
To test it, use postman
RUNNING ON DUAL MONITORS / DOCKING STATION ?
A) Run the emulator with everything unplugged, then plug back in your monitor! (Odd I know)... OR Better yet...
B) Create a New Hardware Profile, which will enable you to change Graphics: Automatic to Software.
You can run Rundll32.exe for IE Options control panel applet and achieve following tasks.
Deletes ALL History - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 255
Deletes History Only - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 1
Deletes Cookies Only - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 2
Deletes Temporary Internet Files Only - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 8
Deletes Form Data Only - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 16
Deletes Password History Only - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 32
This is also an alternate use of case-when...
UPDATE [dbo].[JobTemplates]
SET [CycleId] =
CASE [Id]
WHEN 1376 THEN 44 --ACE1 FX1
WHEN 1385 THEN 44 --ACE1 FX2
WHEN 1574 THEN 43 --ACE1 ELEM1
WHEN 1576 THEN 43 --ACE1 ELEM2
WHEN 1581 THEN 41 --ACE1 FS1
WHEN 1585 THEN 42 --ACE1 HS1
WHEN 1588 THEN 43 --ACE1 RS1
WHEN 1589 THEN 44 --ACE1 RM1
WHEN 1590 THEN 43 --ACE1 ELEM3
WHEN 1591 THEN 43 --ACE1 ELEM4
WHEN 1595 THEN 44 --ACE1 SSTn
ELSE 0
END
WHERE
[Id] IN (1376,1385,1574,1576,1581,1585,1588,1589,1590,1591,1595)
I like the use of the temporary tables in cases where duplicate values are not permitted and your update may create them. For example:
SELECT
[Id]
,[QueueId]
,[BaseDimensionId]
,[ElastomerTypeId]
,CASE [CycleId]
WHEN 29 THEN 44
WHEN 30 THEN 43
WHEN 31 THEN 43
WHEN 101 THEN 41
WHEN 102 THEN 43
WHEN 116 THEN 42
WHEN 120 THEN 44
WHEN 127 THEN 44
WHEN 129 THEN 44
ELSE 0
END AS [CycleId]
INTO
##ACE1_PQPANominals_1
FROM
[dbo].[ProductionQueueProcessAutoclaveNominals]
WHERE
[QueueId] = 3
ORDER BY
[BaseDimensionId], [ElastomerTypeId], [Id];
---- (403 row(s) affected)
UPDATE [dbo].[ProductionQueueProcessAutoclaveNominals]
SET
[CycleId] = X.[CycleId]
FROM
[dbo].[ProductionQueueProcessAutoclaveNominals]
INNER JOIN
(
SELECT
MIN([Id]) AS [Id],[QueueId],[BaseDimensionId],[ElastomerTypeId],[CycleId]
FROM
##ACE1_PQPANominals_1
GROUP BY
[QueueId],[BaseDimensionId],[ElastomerTypeId],[CycleId]
) AS X
ON
[dbo].[ProductionQueueProcessAutoclaveNominals].[Id] = X.[Id];
----(375 row(s) affected)
You could simply do:
Select Req_ID, (avg(R1)+avg(R2)+avg(R3)+avg(R4)+avg(R5))/5 as Average
from Request
Group by Req_ID
Right?
I'm assuming that you may have multiple rows with the same Req_ID and in these cases you want to calculate the average across all columns and rows for those rows with the same Req_ID
Add these both permission of read and write, to solve this issue
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Add this below line in Application tag
android:requestLegacyExternalStorage="true"
Not sure where you get your legends from but:
<button>
As with:
<button type="submit">(html content)</button>
IE6 will submit all text for this button between the tags, other browsers will only submit the value. Using <button>
gives you more layout freedom over the design of the button. In all its intents and purposes, it seemed excellent at first, but various browser quirks make it hard to use at times.
In your example, IE6 will send text
to the server, while most other browsers will send nothing. To make it cross-browser compatible, use <button type="submit" value="text">text</button>
. Better yet: don't use the value, because if you add HTML it becomes rather tricky what is received on server side. Instead, if you must send an extra value, use a hidden field.
<input>
As with:
<input type="button" />
By default, this does next to nothing. It will not even submit your form. You can only place text on the button and give it a size and a border by means of CSS. Its original (and current) intent was to execute a script without the need to submit the form to the server.
<input>
As with:
<input type="submit" />
Like the former, but actually submits the surrounding form.
<input>
As with:
<input type="image" />
Like the former (submit), it will also submit a form, but you can use any image. This used to be the preferred way to use images as buttons when a form needed submitting. For more control, <button>
is now used. This can also be used for server side image maps but that's a rarity these days. When you use the usemap
-attribute and (with or without that attribute), the browser will send the mouse-pointer X/Y coordinates to the server (more precisely, the mouse-pointer location inside the button of the moment you click it). If you just ignore these extras, it is nothing more than a submit button disguised as an image.
There are some subtle differences between browsers, but all will submit the value-attribute, except for the <button>
tag as explained above.
Dhaust gives a good way to add the property to the ApplicationUser class. Looking at the OP code it appears they may have done this or were on track to do that. The question asks
How can I retrieve the OrganizationId property of the currently logged in user from within a controller? However, OrganizationId is not a property available in User.Identity. Do I need to extend User.Identity to include the OrganizationId property?
Pawel gives a way to add an extension method that requires using statements or adding the namespace to the web.config file.
However, the question asks if you "need to" extend User.Identity to include the new property. There is an alternative way to access the property without extending User.Identity. If you followed Dhaust method you can then use the following code in your controller to access the new property.
ApplicationDbContext db = new ApplicationDbContext();
var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db));
var currentUser = manager.FindById(User.Identity.GetUserId());
var myNewProperty = currentUser.OrganizationId;
You can do this without any JavaScript involved
(Using accepted answer)
HTML
<table class="table table-bordered table-striped">
<tr>
<td><button class="btn" data-target="#collapseme" data-toggle="collapse" type="button">Click to expand</button></td>
</tr>
<tr>
<td class="nopadding">
<div class="collapse" id="collapseme">
<div class="content">
Show me collapsed
</div>
</div>
</td>
</tr>
</table>
CSS
.nopadding {
padding: 0 !important;
}
.content {
padding: 20px;
}
Instead of modding the auto-generated code or wrapping every call in duplicate code, you can inject your custom HTTP headers by adding a custom message inspector, it's easier than it sounds:
public class CustomMessageInspector : IClientMessageInspector
{
readonly string _authToken;
public CustomMessageInspector(string authToken)
{
_authToken = authToken;
}
public object BeforeSendRequest(ref Message request, IClientChannel channel)
{
var reqMsgProperty = new HttpRequestMessageProperty();
reqMsgProperty.Headers.Add("Auth-Token", _authToken);
request.Properties[HttpRequestMessageProperty.Name] = reqMsgProperty;
return null;
}
public void AfterReceiveReply(ref Message reply, object correlationState)
{ }
}
public class CustomAuthenticationBehaviour : IEndpointBehavior
{
readonly string _authToken;
public CustomAuthenticationBehaviour (string authToken)
{
_authToken = authToken;
}
public void Validate(ServiceEndpoint endpoint)
{ }
public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
{ }
public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
{ }
public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
{
clientRuntime.ClientMessageInspectors.Add(new CustomMessageInspector(_authToken));
}
}
And when instantiating your client class you can simply add it as a behavior:
this.Endpoint.EndpointBehaviors.Add(new CustomAuthenticationBehaviour("Auth Token"));
This will make every outgoing service call to have your custom HTTP header.
That can be done in short as:
Model::pluck('column')
where model is the Model such as User
model & column as column name like id
if you do
User::pluck('id') // [1,2,3, ...]
& of course you can have any other clauses like where
clause before pluck
In the generated constructor code it should call OnContextCreated()
I added this partial class to solve the problem:
partial class MyContext: ObjectContext
{
partial void OnContextCreated()
{
this.CommandTimeout = 300;
}
}
Google does offer naked domain redirection.
Simply run the command:
C:>python .\file_name.py
Assuming the file name is within same folder and Python has already been added to environment variables.
Try this:
import cv2
import cv
color_img = cv2.cvtColor(gray_img, cv.CV_GRAY2RGB)
I discovered, while using opencv, that some of the constants are defined in the cv2 module, and other in the cv module.
Here is a simple example similar to Sachin's. It's recommended to use a "using" statement on the unmanaged file resource:
// using System.IO;
string filepath = @"C:\test.txt";
using (StreamWriter writer = new StreamWriter(filepath))
{
writer.WriteLine("some text");
}
Simple run your project online i.e mvn clean install
. It fetches all the latest dependencies that you mention in your pom.xml and built the project
I dont know why you havent marked on of these gr8 answers... here is another option which would enable you and anyone else visiting to control transition speed and pause time
JAVASCRIPT
$(function () {
/* SET PARAMETERS */
var change_img_time = 5000;
var transition_speed = 100;
var simple_slideshow = $("#exampleSlider"),
listItems = simple_slideshow.children('li'),
listLen = listItems.length,
i = 0,
changeList = function () {
listItems.eq(i).fadeOut(transition_speed, function () {
i += 1;
if (i === listLen) {
i = 0;
}
listItems.eq(i).fadeIn(transition_speed);
});
};
listItems.not(':first').hide();
setInterval(changeList, change_img_time);
});
.
HTML
<ul id="exampleSlider">
<li><img src="http://placehold.it/500x250" alt="" /></li>
<li><img src="http://placehold.it/500x250" alt="" /></li>
<li><img src="http://placehold.it/500x250" alt="" /></li>
<li><img src="http://placehold.it/500x250" alt="" /></li>
</ul>
.
If your keeping this simple its easy to keep it resposive
best to visit the: DEMO
.
If you want something with special transition FX (Still responsive) - check this out
DEMO WITH SPECIAL FX
Based on my experience with AngularJS modals so far I believe that the most elegant approach is a dedicated service to which we can provide a partial (HTML) template to be displayed in a modal.
When we think about it modals are kind of AngularJS routes but just displayed in modal popup.
The AngularUI bootstrap project (http://angular-ui.github.com/bootstrap/) has an excellent $modal
service (used to be called $dialog prior to version 0.6.0) that is an implementation of a service to display partial's content as a modal popup.
I suggest to learn it with printf because for many cases this will be sufficient for your needs and you won't need to create other objects.
double d = 3.14159;
printf ("%.2f", d);
But if you need rounding please refer to this post
Firebug 2 does now incorporate DOM events debugging / inspection.
For reading a xlsx file we can use Apache POI libs Try this:
public static void readXLSXFile() throws IOException
{
InputStream ExcelFileToRead = new FileInputStream("C:/Test.xlsx");
XSSFWorkbook wb = new XSSFWorkbook(ExcelFileToRead);
XSSFWorkbook test = new XSSFWorkbook();
XSSFSheet sheet = wb.getSheetAt(0);
XSSFRow row;
XSSFCell cell;
Iterator rows = sheet.rowIterator();
while (rows.hasNext())
{
row=(XSSFRow) rows.next();
Iterator cells = row.cellIterator();
while (cells.hasNext())
{
cell=(XSSFCell) cells.next();
if (cell.getCellType() == XSSFCell.CELL_TYPE_STRING)
{
System.out.print(cell.getStringCellValue()+" ");
}
else if(cell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC)
{
System.out.print(cell.getNumericCellValue()+" ");
}
else
{
//U Can Handel Boolean, Formula, Errors
}
}
System.out.println();
}
}
Unfortunately the standard DNS A-record (domain name to IP address) used by web-browsers to locate web-servers does not include a port number. Web-browsers use the URL protocol prefix (http://) to determine the port number (http = 80, https = 443, ftp = 21, etc.) unless the port number is specifically typed in the URL (for example "http://www.simpledns.com:5000" = port 5000).
Can I specify a TCP/IP port number for my web-server in DNS? (Other than the standard port 80)
If both database on same server. You can check similar tables by using following query :
select
fdb.name, sdb.name
from
FIRSTDBNAME.sys.tables fdb
join SECONDDBNAME.sys.tables sdb
on fdb.name = sdb.name -- compare same name tables
order by
1
By listing out similar table you can compare columns schema using sys.columns
view.
Hope this helps you.
check this.. Brief:Pick each element of array and compare it with all elements of the array, weather it is equal to the picked on or not.
int popularity1 = 0;
int popularity2 = 0;
int popularity_item, array_item; //Array contains integer value. Make it String if array contains string value.
for(int i =0;i<array.length;i++){
array_item = array[i];
for(int j =0;j<array.length;j++){
if(array_item == array[j])
popularity1 ++;
{
if(popularity1 >= popularity2){
popularity_item = array_item;
popularity2 = popularity1;
}
popularity1 = 0;
}
//"popularity_item" contains the most repeted item in an array.
driver.manage().window().maximize();
driver.maximize_window()
@driver.manage.window.maximize
OR
max_width, max_height = driver.execute_script("return [window.screen.availWidth, window.screen.availHeight];")
@driver.manage.window.resize_to(max_width, max_height)
OR
target_size = Selenium::WebDriver::Dimension.new(1600, 1268)
@driver.manage.window.size = target_size
Python is very sensitive to indentation, with the code below I got the same error:
except IntegrityError as e:
if 'unique constraint' in e.args:
return render(request, "calender.html")
The correct indentation is:
except IntegrityError as e:
if 'unique constraint' in e.args:
return render(request, "calender.html")
For anything with requests to URLs you might want to check out requests. For JSON in particular:
>>> import requests
>>> r = requests.get('https://github.com/timeline.json')
>>> r.json()
[{u'repository': {u'open_issues': 0, u'url': 'https://github.com/...
This code is working fine for me,
var a = serializer.Deserialize<List<Entity>>(json);
If you want to add a primary key constraint to an existing column all of the previously listed syntax will fail.
To add a primary key constraint to an existing column use the form:
ALTER TABLE `goods`
MODIFY COLUMN `id` INT(10) UNSIGNED PRIMARY KEY AUTO_INCREMENT;
Attribute_Brands is a named range that should contain your list items. Use the drop down to the left of the formula bar to jump to the named range, then edit it. If you add or remove items you will need to adjust the range the named range covers.
If you're having an issue where the Resources added are images and are not getting copied to your build folder on compiling. You need to change the "Build Action" to None from Resource ( which is the default) and change the Copy to "If Newer" or "Always" as shown below :
Using the lambda function to check the character is "_" then only count will be incremented else not a valid character
std::string s = "a_b_c";
size_t count = std::count_if( s.begin(), s.end(), []( char c ){if(c =='_') return true; });
std::cout << "The count of numbers: " << count << std::endl;
Try specifying a DC in DomainB using the -Server
property. Ex:
Get-ADUser -Server "dc01.DomainB.local" -Filter {EmailAddress -like "*Smith_Karla*"} -Properties EmailAddress
I've solved this issue by using ETag
Etags are similar to fingerprints, and if the resource at a given URL changes, a new Etag value must be generated. A comparison of them can determine whether two representations of a resource are the same.
Took me a while to find the new place for expection settings, therefore a new answer.
Since Visual Studio 2015 you control which Exceptions to stop on in the Exception Settings Window (Debug->Windows->Exception Settings). The shortcut is still Ctrl-Alt-E.
The simplest way to handle custom exceptions is selecting "all exceptions not in this list".
Here is a screenshot from the english version:
Here is a screenshot from the german version:
The format you need is:
'2007-01-01 10:00:00'
i.e. yyyy-MM-dd HH:mm:ss
If possible, however, use a parameterised query as this frees you from worrying about the formatting details.
Just to throw my 2 cents in, this worked for me:
extension UIButton {
public func centerImageAndTextVertically(spacing: CGFloat) {
layoutIfNeeded()
let contentFrame = contentRect(forBounds: bounds)
let imageFrame = imageRect(forContentRect: contentFrame)
let imageLeftInset = bounds.size.width * 0.5 - imageFrame.size.width * 0.5
let imageTopInset = -(imageFrame.size.height + spacing * 0.5)
let titleFrame = titleRect(forContentRect: contentFrame)
let titleLeftInset = ((bounds.size.width - titleFrame.size.width) * 0.5) - imageFrame.size.width
let titleTopInmset = titleFrame.size.height + spacing * 0.5
imageEdgeInsets = UIEdgeInsets(top: imageTopInset, left: imageLeftInset, bottom: 0, right: 0)
titleEdgeInsets = UIEdgeInsets(top: titleTopInmset, left: titleLeftInset, bottom: 0, right: 0)
}
}
It's also worth noting that you can use *
and **
when calling functions as well. This is a shortcut that allows you to pass multiple arguments to a function directly using either a list/tuple or a dictionary. For example, if you have the following function:
def foo(x,y,z):
print("x=" + str(x))
print("y=" + str(y))
print("z=" + str(z))
You can do things like:
>>> mylist = [1,2,3]
>>> foo(*mylist)
x=1
y=2
z=3
>>> mydict = {'x':1,'y':2,'z':3}
>>> foo(**mydict)
x=1
y=2
z=3
>>> mytuple = (1, 2, 3)
>>> foo(*mytuple)
x=1
y=2
z=3
Note: The keys in mydict
have to be named exactly like the parameters of function foo
. Otherwise it will throw a TypeError
:
>>> mydict = {'x':1,'y':2,'z':3,'badnews':9}
>>> foo(**mydict)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: foo() got an unexpected keyword argument 'badnews'
If you open the references folder and locate system.data.entity, click the item, then check the runtime version number in the Properties explorer, you will see the sub version as well. Mine for instance shows v4.0.30319 with the Version property showing 4.0.0.0.
Use non-greedy matching, if your engine supports it. Add the ? inside the capture.
/location="(.*?)"/
Add this to .gitignore:
*
!.gitignore
yourElement.setAttribute("style", "background-color:red; font-size:2em;");
Or you could write the element as pure HTML and use .innerHTML = [raw html code]
... that's very ugly though.
In answer to your first question, first you use var myElement = createElement(...);
, then you do document.body.appendChild(myElement);
.
You need a loop over the lines of a file, you need to learn about string methods
with open(filename,'r') as f:
for line in f.readlines():
# python can do regexes, but this is for s fixed string only
if "something" in line:
idx1 = line.find('"')
idx2 = line.find('"', idx1+1)
field = line[idx1+1:idx2-1]
print(field)
and you need a method to pass the filename to your python program and while you are at it, maybe also the string to search for...
For the future, try to ask more focused questions if you can,
Using awk
:
awk '/cdef/{print $0 RS "line1" RS "line2" RS "line3" RS "line4";next}1' input.txt
Explanation:
/.../
print $0
RS
is built-in awk
variable that is by default set to new-line
. 1
at the end results in printing of every other lines. Using next
before it allows us to prevent the current line since you have already printed it using print $0
.
$ awk '/cdef/{print $0 RS "line1" RS "line2" RS "line3" RS "line4";next}1' input.txt
abcd
accd
cdef
line1
line2
line3
line4
line
web
To make changes to the file you can do:
awk '...' input.txt > tmp && mv tmp input.txt
React Hooks (16.8+):
const Dropdown = ({
options
}) => {
const [selectedOption, setSelectedOption] = useState(options[0].value);
return (
<select
value={selectedOption}
onChange={e => setSelectedOption(e.target.value)}>
{options.map(o => (
<option key={o.value} value={o.value}>{o.label}</option>
))}
</select>
);
};
You can also check this collection of UIKit and Foundation categories: https://github.com/leszek-s/LSCategories
It allows adding border on one side of UIView with single line of code:
[self.someView lsAddBorderOnEdge:UIRectEdgeTop color:[UIColor blueColor] width:2];
and it properly handles view rotation while most of answers posted here do not handle it well.
Hibernate definitely supports this. From the docs:
"Generated properties are properties which have their values generated by the database. Typically, Hibernate applications needed to refresh objects which contain any properties for which the database was generating values. Marking properties as generated, however, lets the application delegate this responsibility to Hibernate. Essentially, whenever Hibernate issues an SQL INSERT or UPDATE for an entity which has defined generated properties, it immediately issues a select afterwards to retrieve the generated values."
For properties generated on insert only, your property mapping (.hbm.xml) would look like:
<property name="foo" generated="insert"/>
For properties generated on insert and update your property mapping (.hbm.xml) would look like:
<property name="foo" generated="always"/>
Unfortunately, I don't know JPA, so I don't know if this feature is exposed via JPA (I suspect possibly not)
Alternatively, you should be able to exclude the property from inserts and updates, and then "manually" call session.refresh( obj ); after you have inserted/updated it to load the generated value from the database.
This is how you would exclude the property from being used in insert and update statements:
<property name="foo" update="false" insert="false"/>
Again, I don't know if JPA exposes these Hibernate features, but Hibernate does support them.
(function($){
$.html2text = function(html) {
if($('#scratch_pad').length === 0) {
$('<div id="lh_scratch"></div>').appendTo('body');
}
return $('#scratch_pad').html(html).text();
};
})(jQuery);
Define this as a jquery plugin and use it like as follows:
$.html2text(htmlContent);
You have two options:
1. Share via ?Boot
function in App\Providers\AppServiceProvider
:
public function boot()
{
view()->share('key', 'value');
}
And access $key
variable in any view file.
Note
: Remember that you can't access current Session
, Auth
, Route
data here. This option is good only if you want to share static data. Suppose you want to share some data based on the current user , route, or any custom session variable you won't be able to do with this.
2. Use of a helper class:
Create a helper class anywhere in your application and register it in Alias array in app.php
file in config
folder.
'aliases' => [
...,
'Helper' => App\HelperClass\Helper::class,
],
and create Helper.php
in HelperClass folder within App folder:
namespace App\HelperClass;
class Helper
{
public static function Sample()
{
//Your Code Here
}
}
and access it anywhere like Helper::Sample()
.
You will not be restricted
here to use Auth
, Route
, Session
, or any other classes.
I received the same error while uploading a flutter app to playstore simply change the version code in pubspec.yaml worked for me. may be try changing the version code e.g from +1 to +2 and then rebuild the apk using
flutter build apk --split-per-abi
and upload all the apk's to the playstore for your users. Next time when you want to push an update make sure to update the version code to +3 and so on.
Note: that the version code and version name are different you can see that in android/local.properties file. e.g version: 1.0.0+2
version is 1.0.0 and verison code is +2
This worked for me:
http://codepen.io/anon/pen/qNbWwK
Hide the default buttons in CSS and use:
<!-- In HTML: -->
<p class="left">left</p>
<p class="right">right</p>
/* In the JS file */
$('.slider').slick({
arrows: false
})
$('.left').click(function(){
$('.slider').slick('slickPrev');
})
$('.right').click(function(){
$('.slider').slick('slickNext');
})
@ImportanceOfBeingErnest 's answer is good if you only want to change the linewidth inside the legend box. But I think it is a bit more complex since you have to copy the handles before changing legend linewidth. Besides, it can not change the legend label fontsize. The following two methods can not only change the linewidth but also the legend label text font size in a more concise way.
import numpy as np
import matplotlib.pyplot as plt
# make some data
x = np.linspace(0, 2*np.pi)
y1 = np.sin(x)
y2 = np.cos(x)
# plot sin(x) and cos(x)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y1, c='b', label='y1')
ax.plot(x, y2, c='r', label='y2')
leg = plt.legend()
# get the individual lines inside legend and set line width
for line in leg.get_lines():
line.set_linewidth(4)
# get label texts inside legend and set font size
for text in leg.get_texts():
text.set_fontsize('x-large')
plt.savefig('leg_example')
plt.show()
import numpy as np
import matplotlib.pyplot as plt
# make some data
x = np.linspace(0, 2*np.pi)
y1 = np.sin(x)
y2 = np.cos(x)
# plot sin(x) and cos(x)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y1, c='b', label='y1')
ax.plot(x, y2, c='r', label='y2')
leg = plt.legend()
# get the lines and texts inside legend box
leg_lines = leg.get_lines()
leg_texts = leg.get_texts()
# bulk-set the properties of all lines and texts
plt.setp(leg_lines, linewidth=4)
plt.setp(leg_texts, fontsize='x-large')
plt.savefig('leg_example')
plt.show()
The above two methods produce the same output image:
C99 is available online. Quoted from www.open-std.org:
The lastest publically available version of the standard is the combined C99 + TC1 + TC2 + TC3, WG14 N1256, dated 2007-09-07. This is a WG14 working paper, but it reflects the consolidated standard at the time of issue.
<input id="widget-wpb_widget-3-custom_date" class="mycheck" type="checkbox" value="d/M/y" name="widget-wpb_widget[3][custom_date]" unchecked="true">
var atrib = $('.mycheck').attr("unchecked",true);
$('.mycheck').click(function(){
if ($(this).is(":checked"))
{
$('.mycheck').attr("unchecked",false);
alert("checkbox checked");
}
else
{
$('.mycheck').attr("unchecked",true);
alert("checkbox unchecked");
}
});
To properly display one div on top of another, we need to use the property position
as follows:
position: relative
position: absolute
I found a good example here:
.dvContainer {_x000D_
position: relative;_x000D_
display: inline-block;_x000D_
width: 300px;_x000D_
height: 200px;_x000D_
background-color: #ccc;_x000D_
}_x000D_
_x000D_
.dvInsideTL {_x000D_
position: absolute;_x000D_
left: 0;_x000D_
top: 0;_x000D_
width: 150px;_x000D_
height: 100px;_x000D_
background-color: #ff751a;_x000D_
opacity: 0.5;_x000D_
}
_x000D_
<div class="dvContainer">_x000D_
<table style="width:100%;height:100%;">_x000D_
<tr>_x000D_
<td style="width:50%;text-align:center">Top Left</td>_x000D_
<td style="width:50%;text-align:center">Top Right</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td style="width:50%;text-align:center">Bottom Left</td>_x000D_
<td style="width:50%;text-align:center">Bottom Right</td>_x000D_
</tr>_x000D_
</table>_x000D_
<div class="dvInsideTL">_x000D_
</div>_x000D_
</div>
_x000D_
I hope this helps,
Zag.