If you like Eclipse for Java, I suggest Eclipse CDT. Despite C/C++ support isn't so powerful as is for Java, it still offers most of the features. It has a nice feature named Managed Project that makes working with C/C++ projects easier if you don't have experience with Makefiles. But you can still use Makefiles. I do C and Java coding and I'm really happy with CDT. I'm developing the firmware for a embedded device in C and a application in Java that talks to this device, and is really nice to use the same environment for both. I guess it probably makes me more productive.
On most browsers inactive tabs have low priority execution and this can affect JavaScript timers.
If the values of your transition were calculated using real time elapsed between frames instead fixed increments on each interval, you not only workaround this issue but also can achieve a smother animation by using requestAnimationFrame as it can get up to 60fps if the processor isn't very busy.
Here's a vanilla JavaScript example of an animated property transition using requestAnimationFrame
:
var target = document.querySelector('div#target')_x000D_
var startedAt, duration = 3000_x000D_
var domain = [-100, window.innerWidth]_x000D_
var range = domain[1] - domain[0]_x000D_
_x000D_
function start() {_x000D_
startedAt = Date.now()_x000D_
updateTarget(0)_x000D_
requestAnimationFrame(update)_x000D_
}_x000D_
_x000D_
function update() {_x000D_
let elapsedTime = Date.now() - startedAt_x000D_
_x000D_
// playback is a value between 0 and 1_x000D_
// being 0 the start of the animation and 1 its end_x000D_
let playback = elapsedTime / duration_x000D_
_x000D_
updateTarget(playback)_x000D_
_x000D_
if (playback > 0 && playback < 1) {_x000D_
// Queue the next frame_x000D_
requestAnimationFrame(update)_x000D_
} else {_x000D_
// Wait for a while and restart the animation_x000D_
setTimeout(start, duration/10)_x000D_
}_x000D_
}_x000D_
_x000D_
function updateTarget(playback) {_x000D_
// Uncomment the line below to reverse the animation_x000D_
// playback = 1 - playback_x000D_
_x000D_
// Update the target properties based on the playback position_x000D_
let position = domain[0] + (playback * range)_x000D_
target.style.left = position + 'px'_x000D_
target.style.top = position + 'px'_x000D_
target.style.transform = 'scale(' + playback * 3 + ')'_x000D_
}_x000D_
_x000D_
start()
_x000D_
body {_x000D_
overflow: hidden;_x000D_
}_x000D_
_x000D_
div {_x000D_
position: absolute;_x000D_
white-space: nowrap;_x000D_
}
_x000D_
<div id="target">...HERE WE GO</div>
_x000D_
@UpTheCreek comment:
Fine for presentation issues, but still there are some things that you need to keep running.
If you have background tasks that needs to be precisely executed at given intervals, you can use HTML5 Web Workers. Take a look at Möhre's answer below for more details...
This problem and many others could be avoided by using CSS transitions/animations instead of JavaScript based animations which adds a considerable overhead. I'd recommend this jQuery plugin that let's you take benefit from CSS transitions just like the animate()
methods.
To set the use of scientific notation in your entire R session, you can use the scipen
option. From the documentation (?options
):
‘scipen’: integer. A penalty to be applied when deciding to print
numeric values in fixed or exponential notation. Positive
values bias towards fixed and negative towards scientific
notation: fixed notation will be preferred unless it is more
than ‘scipen’ digits wider.
So in essence this value determines how likely it is that scientific notation will be triggered. So to prevent scientific notation, simply use a large positive value like 999
:
options(scipen=999)
Try using safe TryParseExact method
DateTime temp;
string date = "2011-29-01 12:00 am";
DateTime.TryParseExact(date, "yyyy-dd-MM hh:mm tt", CultureInfo.InvariantCulture, DateTimeStyles.None, out temp);
I tried your code, you didn't assign/bind a value to your formControlName.
In HTML file:
<form [formGroup]="form">
<label>
<input type="radio" value="Male" formControlName="gender">
<span>male</span>
</label>
<label>
<input type="radio" value="Female" formControlName="gender">
<span>female</span>
</label>
</form>
In the TS file:
form: FormGroup;
constructor(fb: FormBuilder) {
this.name = 'Angular2'
this.form = fb.group({
gender: ['', Validators.required]
});
}
Make sure you use Reactive form properly: [formGroup]="form"
and you don't need the name attribute.
In my sample. words male
and female
in span tags are the values display along the radio button and Male
and Female
values are bind to formControlName
To make it shorter:
<form [formGroup]="form">
<input type="radio" value='Male' formControlName="gender" >Male
<input type="radio" value='Female' formControlName="gender">Female
</form>
Hope it helps:)
O(n),I would say . I am doing for a balanced tree,applicable for all the trees. Assuming that you use recursion,
T(n) = 2*T(n/2) + 1 ----------> (1)
T(n/2) for left sub-tree and T(n/2) for right sub-tree and '1' for verifying the base case.
On Simplifying (1) you can prove that the traversal(either inorder or preorder or post order) is of order O(n).
If you're using application.properties in spring boot app, then just put the below line into application.properties and it should work:
spring.datasource.url: jdbc:mysql://google/?cloudSqlInstance=&socketFactory=com.google.cloud.sql.mysql.SocketFactory&user=****&password=****
One of the most used tool in the scientific community to that purpose is DummyNet. Once you have installed the ipfw
kernel module, in order to introduce 50ms propagation delay between 2 machines simply run these commands:
./ipfw pipe 1 config delay 50ms
./ipfw add 1000 pipe 1 ip from $IP_MACHINE_1 to $IP_MACHINE_2
In order to also introduce 50% of packet losses you have to run:
./ipfw pipe 1 config plr 0.5
Here more details.
Just came here to share what was happening to me.
You don't need to specify the parent, states work in an document oriented way so, instead of specifying parent: app, you could just change the state to app.index
.config(function($stateProvider, $urlRouterProvider){
$urlRouterProvider.otherwise("/index.html");
$stateProvider.state('app', {
abstract: true,
templateUrl: "tpl.menu.html"
});
$stateProvider.state('app.index', {
url: '/',
templateUrl: "tpl.index.html"
});
$stateProvider.state('app.register', {
url: "/register",
templateUrl: "tpl.register.html"
});
EDIT Warning, if you want to go deep in the nesting, the full path must me specified. For example, you can't have a state like
app.cruds.posts.create
without having a
app
app.cruds
app.cruds.posts
or angular will throw an exception saying it can't figure out the rout. To solve that you can define abstract states
.state('app', {
url: "/app",
abstract: true
})
.state('app.cruds', {
url: "/app/cruds",
abstract: true
})
.state('app/cruds/posts', {
url: "/app/cruds/posts",
abstract: true
})
Oracle has decided to fix Windows XP installation. As of the JRE 8u25 release in 10/15/2014 the code of the installer has been changes so that installation on Windows XP is again possible.
However, this does not mean that Oracle is continuing to support Windows XP. They make no guarantee about current and future releases of JRE8 being compatible with Windows XP. It looks like it's a run at your own risk kind of thing.
See the Oracle blog post here.
You can get the latest JRE8 right off the Oracle downloads site.
It appears that it is possible to track a smart phone without using GPS.
Sources:
Primary: "PinMe: Tracking a Smartphone User around the World"
Secondary: "How to Track a Cellphone Without GPS—or Consent"
I have not yet found a link to the team's final code. When I do I will post, if another has not done so.
If you are using python 3 or above,
>>> list(bytes(b'test'))
[116, 101, 115, 116]
For eg: you are using two activity, if you want to switch over from Activity A to Activity B
Simply give like this.
Intent intent = new Intent(A.this, B.class);
startActivity(intent);
finish();
For those using JaVers, given an audited entity class, you may want to ignore the properties causing the LazyInitializationException
exception (e.g. by using the @DiffIgnore
annotation).
This tells the framework to ignore those properties when calculating the object differences, so it won't try to read from the DB the related objects outside the transaction scope (thus causing the exception).
I'll try to explain it visually:
/**_x000D_
* explaining margins_x000D_
*/_x000D_
_x000D_
body {_x000D_
padding: 3em 15%_x000D_
}_x000D_
_x000D_
.parent {_x000D_
width: 50%;_x000D_
width: 400px;_x000D_
height: 400px;_x000D_
position: relative;_x000D_
background: lemonchiffon;_x000D_
}_x000D_
_x000D_
.parent:before,_x000D_
.parent:after {_x000D_
position: absolute;_x000D_
content: "";_x000D_
}_x000D_
_x000D_
.parent:before {_x000D_
top: 0;_x000D_
bottom: 0;_x000D_
left: 50%;_x000D_
border-left: dashed 1px #ccc;_x000D_
}_x000D_
_x000D_
.parent:after {_x000D_
left: 0;_x000D_
right: 0;_x000D_
top: 50%;_x000D_
border-top: dashed 1px #ccc;_x000D_
}_x000D_
_x000D_
.child {_x000D_
width: 200px;_x000D_
height: 200px;_x000D_
background: rgba(200, 198, 133, .5);_x000D_
}_x000D_
_x000D_
ul {_x000D_
padding: 5% 20px;_x000D_
}_x000D_
_x000D_
.set1 .child {_x000D_
margin: 0;_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
.set2 .child {_x000D_
margin-left: 75px;_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
.set3 .child {_x000D_
margin-left: -75px;_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
_x000D_
/* position absolute */_x000D_
_x000D_
.set4 .child {_x000D_
top: 50%;_x000D_
left: 50%;_x000D_
margin: 0;_x000D_
position: absolute;_x000D_
}_x000D_
_x000D_
.set5 .child {_x000D_
top: 50%;_x000D_
left: 50%;_x000D_
margin-left: 75px;_x000D_
position: absolute;_x000D_
}_x000D_
_x000D_
.set6 .child {_x000D_
top: 50%; /* level from which margin-top starts _x000D_
- downwards, in the case of a positive margin_x000D_
- upwards, in the case of a negative margin _x000D_
*/_x000D_
left: 50%; /* level from which margin-left starts _x000D_
- towards right, in the case of a positive margin_x000D_
- towards left, in the case of a negative margin _x000D_
*/_x000D_
margin: -75px;_x000D_
position: absolute;_x000D_
}
_x000D_
<!-- content to be placed inside <body>…</body> -->_x000D_
<h2><code>position: relative;</code></h2>_x000D_
<h3>Set 1</h3>_x000D_
<div class="parent set 1">_x000D_
<div class="child">_x000D_
<pre>_x000D_
.set1 .child {_x000D_
margin: 0;_x000D_
position: relative;_x000D_
}_x000D_
</pre>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<h3>Set 2</h3>_x000D_
<div class="parent set2">_x000D_
<div class="child">_x000D_
<pre>_x000D_
.set2 .child {_x000D_
margin-left: 75px;_x000D_
position: relative;_x000D_
}_x000D_
</pre>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<h3>Set 3</h3>_x000D_
<div class="parent set3">_x000D_
<div class="child">_x000D_
<pre>_x000D_
.set3 .child {_x000D_
margin-left: -75px;_x000D_
position: relative;_x000D_
}_x000D_
</pre>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<h2><code>position: absolute;</code></h2>_x000D_
_x000D_
<h3>Set 4</h3>_x000D_
<div class="parent set4">_x000D_
<div class="child">_x000D_
<pre>_x000D_
.set4 .child {_x000D_
top: 50%;_x000D_
left: 50%;_x000D_
margin: 0;_x000D_
position: absolute;_x000D_
}_x000D_
</pre>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<h3>Set 5</h3>_x000D_
<div class="parent set5">_x000D_
<div class="child">_x000D_
<pre>_x000D_
.set5 .child {_x000D_
top: 50%;_x000D_
left: 50%;_x000D_
margin-left: 75px;_x000D_
position: absolute;_x000D_
}_x000D_
</pre>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<h3>Set 6</h3>_x000D_
<div class="parent set6">_x000D_
<div class="child">_x000D_
<pre>_x000D_
.set6 .child {_x000D_
top: 50%;_x000D_
left: 50%;_x000D_
margin: -75px;_x000D_
position: absolute;_x000D_
}_x000D_
</pre>_x000D_
</div>_x000D_
</div>
_x000D_
Since none of them all worked for me (select2 4.0.3) is went the std select way.
for(var i = selectbox.options.length - 1 ; i >= 0 ; i--)
selectbox.remove(i);
<?php
include 'cdb.php';
$show=mysqli_query( $conn,"SELECT *FROM 'reg'");
while($row1= mysqli_fetch_array($show))
{
$id=$row1['id'];
$Name= $row1['name'];
$email = $row1['email'];
$username = $row1['username'];
$password= $row1['password'];
$birthm = $row1['bmonth'];
$birthd= $row1['bday'];
$birthy= $row1['byear'];
$gernder = $row1['gender'];
$phone= $row1['phone'];
$image=$row1['image'];
}
?>
<html>
<head><title>hey</head></title></head>
<body>
<form>
<table border="-2" bgcolor="pink" style="width: 12px; height: 100px;" >
<th>
id<input type="text" name="" style="width: 30px;" value= "<?php echo $row1['id']; ?>" >
</th>
<br>
<br>
<th>
name <input type="text" name="" style="width: 60px;" value= "<?php echo $row1['Name']; ?>" >
</th>
<th>
email<input type="text" name="" style="width: 60px;" value= "<?php echo $row1['email']; ?>" >
</th>
<th>
username<input type="hidden" name="" style="width: 60px;" value= "<?php echo $username['email']; ?>" >
</th>
<th>
password<input type="hidden" name="" style="width: 60px;" value= "<?php echo $row1['password']; ?>">
</ths>
<th>
birthday month<input type="text" name="" style="width: 60px;" value= "<?php echo $row1['birthm']; ?>">
</th>
<th>
birthday day<input type="text" name="" style="width: 60px;" value= "<?php echo $row1['birthd']; ?>">
</th>
<th>
birthday year<input type="text" name="" style="width: 60px;" value= "<?php echo $row1['birthy']; ?>" >
</th>
<th>
gender<input type="text" name="" style="width: 60px;" value= "<?php echo $row1['gender']; ?>">
</th>
<th>
phone number<input type="text" name="" style="width: 60px;" value= "<?php echo $row1['phone']; ?>">
</th>
<th>
<th>
image<input type="text" name="" style="width: 60px;" value= "<?php echo $row1['image']; ?>">
</th>
<th>
<font color="pink"> <a href="update.php">update</a></font>
</th>
</table>
</body>
</form>
</body>
</html>
Another useful tool for this from the command line interface, is the pager command.
eg
pager grep -v Sleep | more; show full processlist;
Then you can page through the results.
You can also look for certain users, IPs or queries with grep or sed in this way.
The pager command is persistent per session.
There is good information on curl's page on SSL and certificate issues. I base most of my answer on the information there.
Using strict-ssl false is bad practice and can create issues. What we can do instead is add the certificate that is being injected, by the "man in the middle" certificate.
How to solve this on Windows:
openssl x509 -inform DES -in **rootcert**.cer -out outcert.pem -text
npm config set cafile **C:\Users\username\cacert.pem
npm config set strict-ssl true
Phew! We made it! Now npm can understand how to connect. Bonus is that you can tell curl to use the same cabundle.pem and it will also understand HTTPs.
If you are using the XmlDocument and XmlNode.
Say:
XmlNode f = root.SelectSingleNode("//form[@id='myform']");
Use:
XmlNode s = f.SelectSingleNode(".//input[@type='submit']");
It depends on the tool that you use. But .// will select any child, any depth from a reference node.
You will have to change the value of
post-max-size
upload-max-filesize
both of which you will find in php.ini
Restarting your server will help it start working. On a local test server running XAMIP, i had to stop the Apache server and restart it. It worked fine after that.
In Angular material label with checkbox
<mat-checkbox>Check me!</mat-checkbox>
try to use
<?php require_once($_SERVER['DOCUMENT_ROOT'].'/web/a.php'); ?>
To select and element where you know only the attribute value you can use the below jQuery script
var src = $('.conversation_img[alt="example"]').attr('src');
Please refer the jQuery Documentation for attribute equals selectors
Please also refer to the example in Demo
Following is the code incase you are not able to access the demo..
HTML
<div>
<img alt="example" src="\images\show.jpg" />
<img alt="exampleAll" src="\images\showAll.jpg" />
</div>
SCRIPT JQUERY
var src = $('img[alt="example"]').attr('src');
alert("source of image with alternate text = example - " + src);
var srcAll = $('img[alt="exampleAll"]').attr('src');
alert("source of image with alternate text = exampleAll - " + srcAll );
Output will be
Two Alert messages each having values
I agree with others who recommend using break
. The obvious consequential question is why would anyone recommend otherwise? Well... when you use break, you skip the rest of the code in the block, and the remaining iterations. Sometimes this causes bugs, for example:
a resource acquired at the top of the block may be released at the bottom (this is true even for blocks inside for
loops), but that release step may be accidentally skipped when a "premature" exit is caused by a break
statement (in "modern" C++, "RAII" is used to handle this in a reliable and exception-safe way: basically, object destructors free resources reliably no matter how a scope is exited)
someone may change the conditional test in the for
statement without noticing that there are other delocalised exit conditions
ndim's answer observes that some people may avoid break
s to maintain a relatively consistent loop run-time, but you were comparing break
against use of a boolean early-exit control variable where that doesn't hold
Every now and then people observing such bugs realise they can be prevented/mitigated by this "no breaks" rule... indeed, there's a whole related strategy for "safer" programming called "structured programming", where each function is supposed to have a single entry and exit point too (i.e. no goto, no early return). It may eliminate some bugs, but it doubtless introduces others. Why do they do it?
You can use Google PDF Viewer to read your pdf online:
WebView webview = (WebView) findViewById(R.id.webview);
webview.getSettings().setJavaScriptEnabled(true);
String pdf = "http://www.adobe.com/devnet/acrobat/pdfs/pdf_open_parameters.pdf";
webview.loadUrl("https://drive.google.com/viewerng/viewer?embedded=true&url=" + pdf);
I noticed this wasn't working with a static-first-then-reverse-proxy setup. Here's what that looks like:
location @app {
proxy_pass http://localhost:3000$request_uri;
}
location / {
try_files $uri $uri/ @app;
error_page 405 @app;
}
private static bool CompareDictionaries(IDictionary<string, IEnumerable<string>> dict1, IDictionary<string, IEnumerable<string>> dict2)
{
if (dict1.Count != dict2.Count)
{
return false;
}
var keyDiff = dict1.Keys.Except(dict2.Keys);
if (keyDiff.Any())
{
return false;
}
return (from key in dict1.Keys
let value1 = dict1[key]
let value2 = dict2[key]
select value1.Except(value2)).All(diffInValues => !diffInValues.Any());
}
If you are creating an array then there is no difference, however, the following is neater:
String[] suit = {
"spades",
"hearts",
"diamonds",
"clubs"
};
But, if you want to pass an array into a method you have to call it like this:
myMethod(new String[] {"spades", "hearts"});
myMethod({"spades", "hearts"}); //won't compile!
You have a variety of options. One would be to use PHP as the template engine it is:
<?php
// Draw the page
?>
<div>
<h3><a href="#">First</a></h3>
<div>Lorem ipsum dolor sit amet.</div>
</div>
<?php
// Done drawing.
?>
Another would be to use single quotes, which let you leave double quotes unquoted and also support newlines in literals:
<?php
echo '<div>
<h3><a href="#">First</a></h3>
<div>Lorem ipsum dolor sit amet.</div>
</div>';
?>
Another would be to use a HEREDOC, which leaves double quotes untouched, supports newlines, and also expands any variables inside:
<?php
echo <<<EOS
<div>
<h3><a href="#">First</a></h3>
<div>Lorem ipsum dolor sit amet.</div>
</div>
EOS;
?>
The External Dependencies folder is populated by IntelliSense: the contents of the folder do not affect the build at all (you can in fact disable the folder in the UI).
You need to actually include the header (using a #include
directive) to use it. Depending on what that header is, you may also need to add its containing folder to the "Additional Include Directories" property and you may need to add additional libraries and library folders to the linker options; you can set all of these in the project properties (right click the project, select Properties). You should compare the properties with those of the project that does build to determine what you need to add.
From my experience the only (very) slight advantage of the first form is code readability, the second form adds "noise".
But with modern IDEs and code autogeneration (or autocompletion) I strongly recommend using the second form, you won't spend extra time typing curly braces and you'll avoid some of the most frequent bugs.
There are enough energy consuming bugs, people just shoudn't open doors for big wastes of time.
One of the most important rule to remember when writing code is consistency. Every line of code should be written the same way, no matter who wrote it. Being rigorous prevents bugs from "happening" ;)
This is the same with naming clearly & explicitly your variables, methods, files or with correctly indenting them...
When my students accept this fact, they stop fighting against their own sourcecode and they start to see coding as a really interesting, stimulating and creative activity. They challenge their minds, not their nerves !
With WinForms you can use the ErrorProvider in conjunction with the Validating
event to handle the validation of user input. The Validating
event provides the hook to perform the validation and ErrorProvider gives a nice consistent approach to providing the user with feedback on any error conditions.
http://msdn.microsoft.com/en-us/library/system.windows.forms.errorprovider.aspx
Connections have a close
method as specified in PEP-249 (Python Database API Specification v2.0):
import pyodbc
conn = pyodbc.connect('DRIVER=MySQL ODBC 5.1 driver;SERVER=localhost;DATABASE=spt;UID=who;PWD=testest')
csr = conn.cursor()
csr.close()
conn.close() #<--- Close the connection
Since the pyodbc
connection and cursor are both context managers, nowadays it would be more convenient (and preferable) to write this as:
import pyodbc
conn = pyodbc.connect('DRIVER=MySQL ODBC 5.1 driver;SERVER=localhost;DATABASE=spt;UID=who;PWD=testest')
with conn:
crs = conn.cursor()
do_stuff
# conn.commit() will automatically be called when Python leaves the outer `with` statement
# Neither crs.close() nor conn.close() will be called upon leaving the `with` statement!!
See https://github.com/mkleehammer/pyodbc/issues/43 for an explanation for why conn.close() is not called.
Note that unlike the original code, this causes conn.commit()
to be called. Use the outer with
statement to control when you want commit
to be called.
Also note that regardless of whether or not you use the with
statements, per the docs,
Connections are automatically closed when they are deleted (typically when they go out of scope) so you should not normally need to call [
conn.close()
], but you can explicitly close the connection if you wish.
and similarly for cursors (my emphasis):
Cursors are closed automatically when they are deleted (typically when they go out of scope), so calling [
csr.close()
] is not usually necessary.
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;
Java inbuilt libraries support only AIFC, AIFF, AU, SND and WAVE formats. Here I only discussed playing an audio file using Clip only and see the various methods of a clip.
PlayAudio.java
.Audio.java
.PlayAudio.java
import java.io.IOException;
import java.util.Scanner;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
public class PlayAudio {
public static void main(String[] args) throws
UnsupportedAudioFileException, IOException,
LineUnavailableException {
PlayMp3 playMp3;
playMp3=new PlayMp3();
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("Enter Choice :-");
System.out.println("1. Play");
System.out.println("2. pause");
System.out.println("3. resume");
System.out.println("4. restart");
System.out.println("5. stop");
System.out.println(PlayMp3.status);
System.out.println(":::- ");
int c = sc.nextInt();
if (c ==5){
playMp3.stop();
break;
}
switch (c) {
case 1:
playMp3.play();
break;
case 2:
playMp3.pause();
break;
case 3:
playMp3.resume();
break;
case 4:
playMp3.restart();
break;
case 5:
playMp3.stop();
default:
System.out.println("Please Enter Valid Option :-");
}
}
sc.close();
}
}
Audio.java
import javax.sound.sampled.*;
import java.io.File;
import java.io.IOException;
public class Audio {
private String filePath="mp.snd";
public static String status="paused";
private Long currentFrame=0L;
private Clip clip;
private AudioInputStream audioInputStream;
public Audio() throws UnsupportedAudioFileException, IOException, LineUnavailableException {
audioInputStream = AudioSystem.getAudioInputStream(new File(filePath));
clip = AudioSystem.getClip();
clip.open(audioInputStream);
}
public void play(){
clip.start();
status = "playing";
}
public void pause(){
if (status.equals("paused")) {
System.out.println("audio is already paused");
return;
}
currentFrame = clip.getMicrosecondPosition();
clip.stop();
status = "paused";
}
public void resume() throws UnsupportedAudioFileException, IOException, LineUnavailableException {
if (status.equals("play"))
{
System.out.println("Audio is already being playing");
return;
}
clip.close();
//starts again and goes to currentFrame
resetAudioStream();
clip.setMicrosecondPosition(currentFrame);
play();
status="playing";
}
public void restart() throws UnsupportedAudioFileException, IOException, LineUnavailableException {
clip.stop();
clip.close();
resetAudioStream();
currentFrame = 0L;
clip.setMicrosecondPosition(0);
play();
status="Playing from start";
}
public void stop(){
currentFrame = 0L;
clip.stop();
clip.close();
status="stopped";
}
private void resetAudioStream() throws IOException, UnsupportedAudioFileException, LineUnavailableException {
audioInputStream = AudioSystem.getAudioInputStream(new File(filePath).getAbsoluteFile());
clip.open(audioInputStream);
}
}
I clicked on this button and it worked for me.
Here is the screenshot
The following statement is not entirely accurate:
"So if you are calling other functionality, including static classes, from your page, you should be fine"
I am calling a static method that references the session through HttpContext.Current.Session and it is null. However, I am calling the method via a webservice method through ajax using jQuery.
As I found out here you can fix the problem with a simple attribute on the method, or use the web service session object:
There’s a trick though, in order to access the session state within a web method, you must enable the session state management like so:
[WebMethod(EnableSession = true)]
By specifying the EnableSession value, you will now have a managed session to play with. If you don’t specify this value, you will get a null Session object, and more than likely run into null reference exceptions whilst trying to access the session object.
Thanks to Matthew Cosier for the solution.
Just thought I'd add my two cents.
Ed
The right way to do it in SDK V2, without the overload of actually getting the object, is to use S3Client.headObject. Officially backed by AWS Change Log.
Example code:
public boolean exists(String bucket, String key) {
try {
HeadObjectResponse headResponse = client
.headObject(HeadObjectRequest.builder().bucket(bucket).key(key).build());
return true;
} catch (NoSuchKeyException e) {
return false;
}
}
Currently your application support 100 connections in pool. Here is what conn string will look like if you want to increase it to 200:
public static string srConnectionString =
"server=localhost;database=mydb;uid=sa;pwd=mypw;Max Pool Size=200;";
You can investigate how many connections with database your application use, by executing sp_who
procedure in your database. In most cases default connection pool size will be enough.
- Create a Class
with public static final
fields.
- And then you can access these fields from any class using the Class_Name.Field_Name
.
- You can declare the class
as final
, so that the class
can't be extended(Inherited) and modify....
The general rule I follow is not to include any header file unless I have to. So unless I am storing the object of a class as a member variable of my class I won't include it, I'll just use the forward declaration.
Look for this on your Manifest.xml android:icon="@drawable/ic_launcher"
then change the ic_launcher
to the name of your icon which is on your @drawable
folder.
Use Layout Weights. Keep in mind that it is important to set layout_width
as 0dp
on children to make it work as intended.
on parent layout:
weightSum
of parent Layout as 1
(android:weightSum="1"
)on the child layout:
layout_width
as 0dp
(android:layout_width="0dp"
) layout_weight
as 0.5
[half of weight sum fr equal two] (android:layout_weight="0.5"
)weightSum
3layout_weight
: 1weightSum
1layout_weight
: 0.25To split layout to n equal parts:
- parent:
weightSum
n- child:
layout_weight
: 1
<LinearLayout
android:id="@+id/layout_top"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:weightSum="1">
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:orientation="vertical">
<TextView .. />
<EditText .../>
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:orientation="vertical">
<TextView ../>
<EditText ../>
</LinearLayout>
</LinearLayout>
This works for MySQL and is really just an implicit transaction but it should go something like this:
UPDATE Table1 t1, Table2 t2 SET
t2.field = t2.field+2,
t1.field = t1.field+2
WHERE t1.id = t2.foreign_id and t2.id = '123414'
if you are doing updates to multi tables that require multi statements… which is likely possible if you update one, then another based on other conditions… you should use a transaction.
Another opltion covering cases where there might be severar spaces is by using the isspace()
python function.
df[df.col_name.apply(lambda x:x.isspace() == False)] # will only return cases without empty spaces
adding NaN values:
df[(df.col_name.apply(lambda x:x.isspace() == False) & (~df.col_name.isna())]
Have you tried the GNU make documentation? It has a whole section about conditionals with examples.
@@RowCount
will give you the number of records affected by a SQL Statement.
The @@RowCount
works only if you issue it immediately afterwards. So if you are trapping errors, you have to do it on the same line. If you split it up, you will miss out on whichever one you put second.
SELECT @NumRowsChanged = @@ROWCOUNT, @ErrorCode = @@ERROR
If you have multiple statements, you will have to capture the number of rows affected for each one and add them up.
SELECT @NumRowsChanged = @NumRowsChanged + @@ROWCOUNT, @ErrorCode = @@ERROR
if you want to apply separate css classes for same element with conditions in Vue.js you can use the below given method.it worked in my scenario.
html
<div class="Main" v-bind:class="{ Sub: page}" >
in here, Main and Sub are two different class names for same div element. v-bind:class directive is used to bind the sub class in here. page is the property we use to update the classes when it's value changed.
js
data:{
page : true;
}
here we can apply a condition if we needed. so, if the page property becomes true element will go with Main and Sub claases css styles. but if false only Main class css styles will be applied.
I had the same issue today.While searching here for solution,I have did silly mistake that is instead of importing
import org.springframework.transaction.annotation.Transactional;
unknowingly i have imported
import javax.transaction.Transactional;
Afer changing it everything worked fine.
So thought of sharing,If somebody does same mistake .
I found that switching to use full html instead of filtered html (below the editor in the Text Format dropdown box) is what fixed this problem for me. Otherwise the style would disappear.
To prevent duplication in memory, resharper is suggesting this:
List<string> myList = new List<string>();
IEnumerable<string> myEnumerable = myList;
List<string> listAgain = myList as List<string>() ?? myEnumerable.ToList();
.ToList() returns a new immutable list. So changes to listAgain does not effect myList in @Tamas Czinege answer. This is correct in most instances for least two reasons: This helps prevent changes in one area effecting the other area (loose coupling), and it is very readable, since we shouldn't be designing code with compiler concerns.
But there are certain instances, like being in a tight loop or working on an embedded or low memory system, where compiler considerations should be taken into consideration.
For each iteration of the ng-repeat loop, line
is a reference to an object in your array. Therefore, to preview the value, use {{line.text}}
.
Similarly, to databind to the text, databind to the same: ng-model="line.text"
. You don't need to use value
when using ng-model (actually you shouldn't).
For a more in-depth look at scopes and ng-repeat, see What are the nuances of scope prototypal / prototypical inheritance in AngularJS?, section ng-repeat.
First start with Joran's excellent answer -- doubtful anything can better that.
Then the following mnemonics may help to remember the distinctions between each. Whilst some are obvious, others may be less so --- for these you'll find justification in Joran's discussions.
Mnemonics
lapply
is a list apply which acts on a list or vector and returns a list.sapply
is a simple lapply
(function defaults to returning a vector or matrix when possible)vapply
is a verified apply (allows the return object type to be prespecified)rapply
is a recursive apply for nested lists, i.e. lists within liststapply
is a tagged apply where the tags identify the subsetsapply
is generic: applies a function to a matrix's rows or columns (or, more generally, to dimensions of an array)Building the Right Background
If using the apply
family still feels a bit alien to you, then it might be that you're missing a key point of view.
These two articles can help. They provide the necessary background to motivate the functional programming techniques that are being provided by the apply
family of functions.
Users of Lisp will recognise the paradigm immediately. If you're not familiar with Lisp, once you get your head around FP, you'll have gained a powerful point of view for use in R -- and apply
will make a lot more sense.
Using Aggs u can easily do that. Writing down query for now.
GET index/_search
{
"size":0,
"aggs": {
"source": {
"terms": {
"field": "field",
"size": 100000
}
}
}
}
This would return the different values of field
with there doc counts.
Use m.toString()
or String.valueOf(m)
. String.valueOf uses toString() but is null safe.
I believe that I have the simplest answer. You don't need the string.h library in this program, nor the stdbool.h library. Simply using pointers and pointer arithmetic will help you become a better C programmer.
Simply return 0 for False (no substring found), or 1 for True (yes, a substring "sub" is found within the overall string "str"):
#include <stdlib.h>
int is_substr(char *str, char *sub)
{
int num_matches = 0;
int sub_size = 0;
// If there are as many matches as there are characters in sub, then a substring exists.
while (*sub != '\0') {
sub_size++;
sub++;
}
sub = sub - sub_size; // Reset pointer to original place.
while (*str != '\0') {
while (*sub == *str && *sub != '\0') {
num_matches++;
sub++;
str++;
}
if (num_matches == sub_size) {
return 1;
}
num_matches = 0; // Reset counter to 0 whenever a difference is found.
str++;
}
return 0;
}
string[] lines = File.ReadLines("c:\\file.txt").ToArray();
Although one wonders why you'll want to do that when ReadAllLines
works just fine.
Or perhaps you just want to enumerate with the return value of File.ReadLines
:
var lines = File.ReadAllLines("c:\\file.txt");
foreach (var line in lines)
{
Console.WriteLine("\t" + line);
}
Iterate through...
for %f in (.\*) do @echo %f
for /D %s in (.\*) do @echo %s
for /R %f in (.\*) do @echo %f
for /R /D %s in (.\*) do @echo %s
Unfortunately I did not find any way to iterate over files and subdirs at the same time.
Just use cygwin with its bash for much more functionality.
Apart from this: Did you notice, that the buildin help of MS Windows is a great resource for descriptions of cmd's command line syntax?
Also have a look here: http://technet.microsoft.com/en-us/library/bb490890.aspx
Add a width to the .child
elements. I personally would use percentages on the margin-left
if you want to have it always 4 per row.
.child {
display: inline-block;
background: blue;
margin: 10px 0 0 2%;
flex-grow: 1;
height: 100px;
width: calc(100% * (1/4) - 10px - 1px);
}
After lots of research, I solve this issue with hint from ofir_aghai answer about script load event.
Basically we need to use $
for jQuery code, but we can't use it till jQuery is loaded. I used document.createElement()
to add a script for jQuery, but the issue is that it takes time to load while the next statement in JavaScript using $
fails. So, I used the below solution.
myscript.js is having code which uses jQuery main.js is used to load both jquery.min.js and myscript.js files making sure that jQuery is loaded.
main.js code
window.load = loadJQueryFile();
var heads = document.getElementsByTagName('head');
function loadJQueryFile(){
var jqueryScript=document.createElement('script');
jqueryScript.setAttribute("type","text/javascript");
jqueryScript.setAttribute("src", "/js/jquery.min.js");
jqueryScript.onreadystatechange = handler;
jqueryScript.onload = handler;
heads[0].appendChild(jqueryScript);
}
function handler(){
var myScriptFile=document.createElement('script');
myScriptFile.setAttribute("type","text/javascript");
myScriptFile.setAttribute("src", "myscript.js");
heads[0].appendChild(myScriptFile);
}
This way it worked. Using loadJQueryFile()
from myscript.js didn't work. It immediately goes to the next statement which uses $
.
Oneliner:
obj = (function(attr, val){ var a = {}; a[attr]=val; return a; })('hash', 5);
Or:
attr = 'hash';
val = 5;
var obj = (obj={}, obj[attr]=val, obj);
Anything shorter?
Using the Date object's methods will could come in handy.
e.g.:
myDate = new Date();
plusSeven = new Date(myDate.setDate(myDate.getDate() + 7));
A common issue you might experience when working on a Laravel application is the exception:
RuntimeException No application encryption key has been specified.
You'll often run into this when you pull down an existing Laravel application, where you copy the .env.example
file to .env
but don't set a value for the APP_KEY
variable.
At the command line, issue the following Artisan command to generate a key:
php artisan key:generate
This will generate a random key for APP_KEY
, After completion of .env
edit please enter this command in your terminal for clear cache:php artisan config:cache
Also, If you are using the PHP's default web server (eg. php artisan serve
) you need to restart the server changing your .env
file values. now you will not get to see this error message.
You can use "Overrides" in Chrome to persist javascript changes between page loads, even where you aren't hosting the original source.
You can do something like
$(this).unbind('click').click();
Simple use this to show the alert message box in code behind.
ScriptManager.RegisterStartupScript(this, this.GetType(), "script", "alert('Record Saved Sucessfully');", true);
The cex
parameter will do that for you.
a <- c(3, 2, 2, 2, 1, 2 )
barplot(a, beside = T,
col = 1:6, space = c(0, 2))
legend("topright",
legend = c("a", "b", "c", "d", "e", "f"),
fill = 1:6, ncol = 2,
cex = 0.75)
Just use the below code to resolve this:
JsonObject obj = Json.createReader(new ByteArrayInputStream(Base64.getDecoder().decode(accessToken.split("\\.")[1].
replace('-', '+').replace('_', '/')))).readObject();
In the above code replace('-', '+').replace('_', '/')
did the job. For more details see the https://jwt.io/js/jwt.js. I understood the problem from the part of the code got from that link:
function url_base64_decode(str) {
var output = str.replace(/-/g, '+').replace(/_/g, '/');
switch (output.length % 4) {
case 0:
break;
case 2:
output += '==';
break;
case 3:
output += '=';
break;
default:
throw 'Illegal base64url string!';
}
var result = window.atob(output); //polifyll https://github.com/davidchambers/Base64.js
try{
return decodeURIComponent(escape(result));
} catch (err) {
return result;
}
}
Download phpseclib v1 and use this code:
<?php
set_include_path(__DIR__ . '/phpseclib1.0.11');
include("Net/SSH2.php");
$key ="MyPassword";
/* ### if using PrivateKey ###
include("Crypt/RSA.php");
$key = new Crypt_RSA();
$key->loadKey(file_get_contents('private-key.ppk'));
*/
$ssh = new Net_SSH2('www.example.com', 22); // Domain or IP
if (!$ssh->login('your_username', $key)) exit('Login Failed');
echo $ssh->exec('pwd');
?>
Download newest phpseclib v2 (requires composer install
at first):
<?php
set_include_path($path=__DIR__ . '/phpseclib-master/phpseclib');
include ($path.'/../vendor/autoload.php');
$loader = new \Composer\Autoload\ClassLoader();
use phpseclib\Net\SSH2;
$key ="MyPassword";
/* ### if using PrivateKey ###
use phpseclib\Crypt\RSA;
$key = new RSA();
$key->load(file_get_contents('private-key.ppk'));
*/
$ssh = new SSH2('www.example.com', 22); // Domain or IP
if (!$ssh->login('your_username', $key)) exit('Login Failed');
echo $ssh->exec('pwd');
?>
p.s. if you get "Connection timed out" then it's probably the issue of HOST/FIREWALL (local or remote) or like that, not a fault of script.
The way you have used the HTML syntax is problematic.
This is how the syntax should be
style="property1:value1;property2:value2"
In your case, this will be the way to do
<h2 style="text-align :center; font-family :tahoma" >TITLE</h2>
A further example would be as follows
<div class ="row">
<button type="button" style= "margin-top : 20px; border-radius: 15px"
class="btn btn-primary">View Full Profile</button>
</div>
If I am not late....
For Firefox, one can import the same har file from Network tab.
msg * /server:127.0.0.1 Type your message here
All of the answers posted so far are correct, an endpoint is simply one end of a communication channel. In the case of OAuth, there are three endpoints you need to be concerned with:
Hope that helps clear things up. Have fun learning about OAuth! Post more questions if you run into any difficulties implementing an OAuth client.
declare @data as varchar(50)
set @data='ciao335'
--get text
Select Left(@Data, PatIndex('%[0-9]%', @Data + '1') - 1) ---->>ciao
--get numeric
Select right(@Data, len(@data) - (PatIndex('%[0-9]%', @Data )-1) ) ---->>335
I use rst2pdf to create a pdf file, since I am more familiar with RST than with HTML. It supports embedding almost any kind of raster or vector images.
It requires reportlab, but I found reportlab is not so straight forward to use (at least for me).
Just to save you too much typos:
foreach($group_membership as $username){
$username->items = array(additional array to add);
}
print_r($group_membership);
... And the answer is:
Set SrcRange = Sheets("Src").Range("A2:A9")
SrcRange.Copy Destination:=Sheets("Dest").Range("A2")
The Set
makes all the difference. Then it works like a charm.
After working on this on and off for a few days, here is the answer I would have wished to find, using pywin32 to keep it nice and self contained.
This is complete working code for one loop-based and one thread-based solution. It may work on both python 2 and 3, although I've only tested the latest version on 2.7 and Win7. The loop should be good for polling code, and the tread should work with more server-like code. It seems to work nicely with the waitress wsgi server that does not have a standard way to shut down gracefully.
I would also like to note that there seems to be loads of examples out there, like this that are almost useful, but in reality misleading, because they have cut and pasted other examples blindly. I could be wrong. but why create an event if you never wait for it?
That said I still feel I'm on somewhat shaky ground here, especially with regards to how clean the exit from the thread version is, but at least I believe there are nothing misleading here.
To run simply copy the code to a file and follow the instructions.
Use a simple flag to terminate thread. The important bit is that "thread done" prints.
For a more elaborate example exiting from an uncooperative server thread see my post about the waitress wsgi server.
# uncomment mainthread() or mainloop() call below
# run without parameters to see HandleCommandLine options
# install service with "install" and remove with "remove"
# run with "debug" to see print statements
# with "start" and "stop" watch for files to appear
# check Windows EventViever for log messages
import socket
import sys
import threading
import time
from random import randint
from os import path
import servicemanager
import win32event
import win32service
import win32serviceutil
# see http://timgolden.me.uk/pywin32-docs/contents.html for details
def dummytask_once(msg='once'):
fn = path.join(path.dirname(__file__),
'%s_%s.txt' % (msg, randint(1, 10000)))
with open(fn, 'w') as fh:
print(fn)
fh.write('')
def dummytask_loop():
global do_run
while do_run:
dummytask_once(msg='loop')
time.sleep(3)
class MyThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
global do_run
do_run = True
print('thread start\n')
dummytask_loop()
print('thread done\n')
def exit(self):
global do_run
do_run = False
class SMWinservice(win32serviceutil.ServiceFramework):
_svc_name_ = 'PyWinSvc'
_svc_display_name_ = 'Python Windows Service'
_svc_description_ = 'An example of a windows service in Python'
@classmethod
def parse_command_line(cls):
win32serviceutil.HandleCommandLine(cls)
def __init__(self, args):
win32serviceutil.ServiceFramework.__init__(self, args)
self.stopEvt = win32event.CreateEvent(None, 0, 0, None) # create generic event
socket.setdefaulttimeout(60)
def SvcStop(self):
servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
servicemanager.PYS_SERVICE_STOPPED,
(self._svc_name_, ''))
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
win32event.SetEvent(self.stopEvt) # raise event
def SvcDoRun(self):
servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
servicemanager.PYS_SERVICE_STARTED,
(self._svc_name_, ''))
# UNCOMMENT ONE OF THESE
# self.mainthread()
# self.mainloop()
# Wait for stopEvt indefinitely after starting thread.
def mainthread(self):
print('main start')
self.server = MyThread()
self.server.start()
print('wait for win32event')
win32event.WaitForSingleObject(self.stopEvt, win32event.INFINITE)
self.server.exit()
print('wait for thread')
self.server.join()
print('main done')
# Wait for stopEvt event in loop.
def mainloop(self):
print('loop start')
rc = None
while rc != win32event.WAIT_OBJECT_0:
dummytask_once()
rc = win32event.WaitForSingleObject(self.stopEvt, 3000)
print('loop done')
if __name__ == '__main__':
SMWinservice.parse_command_line()
You should put your component between an enclosing tag, Which means:
// WRONG!
return (
<Comp1 />
<Comp2 />
)
Instead:
// Correct
return (
<div>
<Comp1 />
<Comp2 />
</div>
)
Edit: Per Joe Clay's comment about the Fragments API
// More Correct
return (
<React.Fragment>
<Comp1 />
<Comp2 />
</React.Fragment>
)
// Short syntax
return (
<>
<Comp1 />
<Comp2 />
</>
)
CGLIB < 2.2 with JRE > 6 could trigger similar errors, see "Should I upgrade to CGLIB 3.0?" and some commentary at Spring SPR-9669.
This is especially true when everything works fine on JRE 6 and simply switching to JRE7 breaks things.
I just use shell codes.. e.g. \x27
or \\x22
as applicable. No hassle, ever really.
Here's a toy Ruby method that works like #permutation.to_a
that might be more legible to crazy people. It's hella slow, but also 5 lines.
def permute(ary)
return [ary] if ary.size <= 1
ary.collect_concat.with_index do |e, i|
rest = ary.dup.tap {|a| a.delete_at(i) }
permute(rest).collect {|a| a.unshift(e) }
end
end
To convert and append an integer, use operator += (or member function concat
):
String stringOne = "A long integer: ";
stringOne += 123456789;
To get the string as type char[]
, use toCharArray():
char charBuf[50];
stringOne.toCharArray(charBuf, 50)
In the example, there is only space for 49 characters (presuming it is terminated by null). You may want to make the size dynamic.
The cost of bringing in String
(it is not included if not used anywhere in the sketch), is approximately 1212 bytes program memory (flash) and 48 bytes RAM.
This was measured using Arduino IDE version 1.8.10 (2019-09-13) for an Arduino Leonardo sketch.
I have a simple and generic hack to perform key/value if statement instead of boolean-only in mustache (and in an extremely readable fashion!) :
function buildOptions (object) {
var validTypes = ['string', 'number', 'boolean'];
var value;
var key;
for (key in object) {
value = object[key];
if (object.hasOwnProperty(key) && validTypes.indexOf(typeof value) !== -1) {
object[key + '=' + value] = true;
}
}
return object;
}
With this hack, an object like this:
var contact = {
"id": 1364,
"author_name": "Mr Nobody",
"notified_type": "friendship",
"action": "create"
};
Will look like this before transformation:
var contact = {
"id": 1364,
"id=1364": true,
"author_name": "Mr Nobody",
"author_name=Mr Nobody": true,
"notified_type": "friendship",
"notified_type=friendship": true,
"action": "create",
"action=create": true
};
And your mustache template will look like this:
{{#notified_type=friendship}}
friendship…
{{/notified_type=friendship}}
{{#notified_type=invite}}
invite…
{{/notified_type=invite}}
You are probably targeting a server without built-in JSTL support (e.g. some version of Tomcat.) You will need to provision your own JSTL tag library.
bsondump collection.bson > collection.json
and then
mongoimport -d <dbname> -c <collection> < collection.json
You must edit permission of data folder.
I use "Root Explorer" (see market) app on root mode.
On top select "Monunted as r/w"
then press over data folder (long click) and find Permission option
Have a somenthing like that
read write execute
User
Group
Others
Make sure that "Others" have a check for read
Then go Eclpse and try again.
Sorry about my english,I hope can help you.
Check bellow code it`s working fine and common model function also
supported more then one join and also supported multiple where condition
order by ,limit.it`s EASY TO USE and REMOVE CODE REDUNDANCY.
================================================================
*Album.php
//put bellow code in your controller
=================================================================
$album_id='';//album id
//pass join table value in bellow format
$join_str[0]['table'] = 'Category';
$join_str[0]['join_table_id'] = 'Category.cat_id';
$join_str[0]['from_table_id'] = 'Album.cat_id';
$join_str[0]['join_type'] = 'left';
$join_str[1]['table'] = 'Soundtrack';
$join_str[1]['join_table_id'] = 'Soundtrack.album_id';
$join_str[1]['from_table_id'] = 'Album.album_id';
$join_str[1]['join_type'] = 'left';
$selected = "Album.*,Category.cat_name,Category.cat_title,Soundtrack.track_title,Soundtrack.track_url";
$albumData= $this->common->select_data_by_condition('Album', array('Soundtrack.album_id' => $album_id), $selected, '', '', '', '', $join_str);
//call common model function
if (!empty($albumData)) {
print_r($albumData); // print album data
}
=========================================================================
Common.php
//put bellow code in your common model file
========================================================================
function select_data_by_condition($tablename, $condition_array = array(), $data = '*', $sortby = '', $orderby = '', $limit = '', $offset = '', $join_str = array()) {
$this->db->select($data);
//if join_str array is not empty then implement the join query
if (!empty($join_str)) {
foreach ($join_str as $join) {
if ($join['join_type'] == '') {
$this->db->join($join['table'], $join['join_table_id'] . '=' . $join['from_table_id']);
} else {
$this->db->join($join['table'], $join['join_table_id'] . '=' . $join['from_table_id'], $join['join_type']);
}
}
}
//condition array pass to where condition
$this->db->where($condition_array);
//Setting Limit for Paging
if ($limit != '' && $offset == 0) {
$this->db->limit($limit);
} else if ($limit != '' && $offset != 0) {
$this->db->limit($limit, $offset);
}
//order by query
if ($sortby != '' && $orderby != '') {
$this->db->order_by($sortby, $orderby);
}
$query = $this->db->get($tablename);
//if limit is empty then returns total count
if ($limit == '') {
$query->num_rows();
}
//if limit is not empty then return result array
return $query->result_array();
}
You are using two WHERE
clauses but only one is allowed. Use it like this:
SELECT table1.f_id FROM table1
INNER JOIN table2 ON table2.f_id = table1.f_id
WHERE
table1.f_com_id = '430'
AND table1.f_status = 'Submitted'
AND table2.f_type = 'InProcess'
The first option gives you more flexibilty:
var $div = $("<div>", {id: "foo", "class": "a"});
$div.click(function(){ /* ... */ });
$("#box").append($div);
And of course .html('*')
overrides the content while .append('*')
doesn't, but I guess, this wasn't your question.
Another good practice is prefixing your jQuery variables with $
:
Is there any specific reason behind using $ with variable in jQuery
Placing quotes around the "class"
property name will make it more compatible with less flexible browsers.
You can use ASP.NET to generate your HTML outside the context of web pages. Here's an article that shows how it can be done.
try this
var configuration = WebConfigurationManager.OpenWebConfiguration("~");
var section = (ConnectionStringsSection)configuration.GetSection("connectionStrings");
section.ConnectionStrings["MyConnectionString"].ConnectionString = "Data Source=...";
configuration.Save();
My code for Xamarin, I am using FrameLayout for this purpose and following is my code:
List<object> content = new List<object>();
object aWebView = new {ContentType="web",Width="300", Height = "300",X="10",Y="30",ContentUrl="http://www.google.com" };
content.Add(aWebView);
object aWebView2 = new { ContentType = "image", Width = "300", Height = "300", X = "20", Y = "40", ContentUrl = "https://www.nasa.gov/sites/default/files/styles/image_card_4x3_ratio/public/thumbnails/image/leisa_christmas_false_color.png?itok=Jxf0IlS4" };
content.Add(aWebView2);
FrameLayout myLayout = (FrameLayout)FindViewById(Resource.Id.frameLayout1);
foreach (object item in content)
{
string contentType = item.GetType().GetProperty("ContentType").GetValue(item, null).ToString();
FrameLayout.LayoutParams param = new FrameLayout.LayoutParams(Convert.ToInt32(item.GetType().GetProperty("Width").GetValue(item, null).ToString()), Convert.ToInt32(item.GetType().GetProperty("Height").GetValue(item, null).ToString()));
param.LeftMargin = Convert.ToInt32(item.GetType().GetProperty("X").GetValue(item, null).ToString());
param.TopMargin = Convert.ToInt32(item.GetType().GetProperty("Y").GetValue(item, null).ToString());
switch (contentType) {
case "web":{
WebView webview = new WebView(this);
//webview.hei;
myLayout.AddView(webview, param);
webview.SetWebViewClient(new WebViewClient());
webview.LoadUrl(item.GetType().GetProperty("ContentUrl").GetValue(item, null).ToString());
break;
}
case "image":
{
ImageView imageview = new ImageView(this);
//webview.hei;
myLayout.AddView(imageview, param);
var imageBitmap = GetImageBitmapFromUrl("https://www.nasa.gov/sites/default/files/styles/image_card_4x3_ratio/public/thumbnails/image/leisa_christmas_false_color.png?itok=Jxf0IlS4");
imageview.SetImageBitmap(imageBitmap);
break;
}
}
}
It was useful for me because I needed the property of view to overlap each other on basis of their appearance, e.g the views get stacked one above other.
This cannot be done with CMake. You have to generate two separate build folders. One for the x86 NMake build and one for the x64 NMake build. You cannot generate a single Visual Studio project covering both architectures with CMake, either.
To build Visual Studio projects from the command line for both 32-bit and 64-bit without starting a Visual Studio command prompt, use the regular Visual Studio generators.
For CMake 3.13 or newer, run the following commands:
cmake -G "Visual Studio 16 2019" -A Win32 -S \path_to_source\ -B "build32"
cmake -G "Visual Studio 16 2019" -A x64 -S \path_to_source\ -B "build64"
cmake --build build32 --config Release
cmake --build build64 --config Release
For earlier versions of CMake, run the following commands:
mkdir build32 & pushd build32
cmake -G "Visual Studio 15 2017" \path_to_source\
popd
mkdir build64 & pushd build64
cmake -G "Visual Studio 15 2017 Win64" \path_to_source\
popd
cmake --build build32 --config Release
cmake --build build64 --config Release
CMake generated projects that use one of the Visual Studio generators can be built from the command line with using the option --build
followed by the build directory. The --config
option specifies the build configuration.
class DataReader
{
Excel.Application xlApp;
Excel.Workbook xlBook;
Excel.Range xlRange;
Excel.Worksheet xlSheet;
public DataTable GetSheetDataAsDataTable(String filePath, String sheetName)
{
DataTable dt = new DataTable();
try
{
xlApp = new Excel.Application();
xlBook = xlApp.Workbooks.Open(filePath);
xlSheet = xlBook.Worksheets[sheetName];
xlRange = xlSheet.UsedRange;
DataRow row=null;
for (int i = 1; i <= xlRange.Rows.Count; i++)
{
if (i != 1)
row = dt.NewRow();
for (int j = 1; j <= xlRange.Columns.Count; j++)
{
if (i == 1)
dt.Columns.Add(xlRange.Cells[1, j].value);
else
row[j-1] = xlRange.Cells[i, j].value;
}
if(row !=null)
dt.Rows.Add(row);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
xlBook.Close();
xlApp.Quit();
}
return dt;
}
}
<input type="text" name="firstname">
<input type="text" name="lastname">
<input type="text" name="email">
<input type="text" name="address">
<input type="text" name="tree[tree1][fruit]">
<input type="text" name="tree[tree1][height]">
<input type="text" name="tree[tree2][fruit]">
<input type="text" name="tree[tree2][height]">
<input type="text" name="tree[tree3][fruit]">
<input type="text" name="tree[tree3][height]">
it should end up like this in the $_POST[] array (PHP format for easy visualization)
$_POST[] = array(
'firstname'=>'value',
'lastname'=>'value',
'email'=>'value',
'address'=>'value',
'tree' => array(
'tree1'=>array(
'fruit'=>'value',
'height'=>'value'
),
'tree2'=>array(
'fruit'=>'value',
'height'=>'value'
),
'tree3'=>array(
'fruit'=>'value',
'height'=>'value'
)
)
)
Now that Javascript has lookbehind (as of ES2018), on newer environments, you can avoid groups entirely in situations like these. Rather, lookbehind for what comes before the group you were capturing, and lookahead for what comes after, and replace with just !NEW_ID!
:
const str = 'name="some_text_0_some_text"';
console.log(
str.replace(/(?<=name="\w+)\d+(?=\w+")/, '!NEW_ID!')
);
_x000D_
With this method, the full match is only the part that needs to be replaced.
(?<=name="\w+)
- Lookbehind for name="
, followed by word characters (luckily, lookbehinds do not have to be fixed width in Javascript!)\d+
- Match one or more digits - the only part of the pattern not in a lookaround, the only part of the string that will be in the resulting match(?=\w+")
- Lookahead for word characters followed by "
`Keep in mind that lookbehind is pretty new. It works in modern versions of V8 (including Chrome, Opera, and Node), but not in most other environments, at least not yet. So while you can reliably use lookbehind in Node and in your own browser (if it runs on a modern version of V8), it's not yet sufficiently supported by random clients (like on a public website).
In general, you typically will want to avoid boxing your value types.
However, there are rare occurances where this is useful. If you need to target the 1.1 framework, for example, you will not have access to the generic collections. Any use of the collections in .NET 1.1 would require treating your value type as a System.Object, which causes boxing/unboxing.
There are still cases for this to be useful in .NET 2.0+. Any time you want to take advantage of the fact that all types, including value types, can be treated as an object directly, you may need to use boxing/unboxing. This can be handy at times, since it allows you to save any type in a collection (by using object instead of T in a generic collection), but in general, it is better to avoid this, as you're losing type safety. The one case where boxing frequently occurs, though, is when you're using Reflection - many of the calls in reflection will require boxing/unboxing when working with value types, since the type is not known in advance.
I don't think you can use braces.
According to the Bash manual about case in Conditional Constructs.
Each pattern undergoes tilde expansion, parameter expansion, command substitution, and arithmetic expansion.
Nothing about Brace Expansion unfortunately.
So you'd have to do something like this:
case $1 in
req*)
...
;;
met*|meet*)
...
;;
*)
# You should have a default one too.
esac
Use the following in a stored procedure:
IF NOT EXISTS( SELECT NULL
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'tablename'
AND table_schema = 'db_name'
AND column_name = 'columnname') THEN
ALTER TABLE `TableName` ADD `ColumnName` int(1) NOT NULL default '0';
END IF;
You can do it easy....
1) create a boolean variable ...
private boolean bolBroacastRegistred;
2) When you register your Broadcast Receiver, set it to TRUE
...
bolBroacastRegistred = true;
this.registerReceiver(mReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
....
3) In the onPause() do it...
if (bolBroacastRegistred) {
this.unregisterReceiver(mReceiver);
bolBroacastRegistred = false
}
Just it, and now, you will not receive more exception error message on onPause().
Tip1: Always use the unregisterReceiver() in onPause() not in onDestroy() Tip2: Dont forget to set the bolBroadcastRegistred variable to FALSE when run the unregisterReceive()
Success!
LENGTH()
does return the string length (just verified). I suppose that your data is padded with blanks - try
SELECT typ, LENGTH(TRIM(t1.typ))
FROM AUTA_VIEW t1;
instead.
As OraNob
mentioned, another cause could be that CHAR
is used in which case LENGTH()
would also return the column width, not the string length. However, the TRIM()
approach also works in this case.
Set both the outline
and the box-shadow
properties of the button to none
and make them important.
input[type="button"] {
outline: none !important;
box-shadow: none !important;
}
The reason for setting the values to important is that, if you are using other CSS libraries or frameworks like Bootstrap, it might get overridden.
I had to edit /etc/apache2/sites-available/default
. The lines are the same as mentioned by RDL.
You are not indicating what to include in the archive.
Go one level outside your folder and try:
sudo tar -cvjSf folder.tar.bz2 folder
Or from the same folder try
sudo tar -cvjSf folder.tar.bz2 *
Cheers!
change this {% if loop.counter == 1 %}
to {% if forloop.counter == 1 %} {#your code here#} {%endfor%}
and this from {{ user }} {{loop.counter}}
to {{ user }} {{forloop.counter}}
In a project, my client would like a floating box in another div, so I use margin-top CSS property rather than top in order to my floating box stay in its parent.
I think your list of reasons is a pretty comprehensive one.
One particularly bad example that I've encountered more than once goes like this:
try {
// do stuff
} catch (Exception e) {
e.printStackTrace(); // and swallow the exception
}
The problem with the above code is that the handling consists entirely of the printStackTrace
call: the exception isn't really handled properly nor is it allowed to escape.
On the other hand, as a rule I always log the stack trace whenever there's an unexpected exception in my code. Over the years this policy has saved me a lot of debugging time.
Finally, on a lighter note, God's Perfect Exception.
This is tricky; the reason it's failing is that you can't position via margin or text-align while absolutely positioned.
If the image is alone in the div, then I recommend something like this:
.image_block {
width: 175px;
height: 175px;
line-height: 175px;
text-align: center;
vertical-align: bottom;
}
You may need to stick the vertical-align
call on the image instead; not really sure without testing it. Using vertical-align
and line-height
is going to treat you a lot better, though, than trying to mess around with absolute positioning.
function isMobileDev(){
if(isset($_SERVER['HTTP_USER_AGENT']) and !empty($_SERVER['HTTP_USER_AGENT'])){
$user_ag = $_SERVER['HTTP_USER_AGENT'];
if(preg_match('/(Mobile|Android|Tablet|GoBrowser|[0-9]x[0-9]*|uZardWeb\/|Mini|Doris\/|Skyfire\/|iPhone|Fennec\/|Maemo|Iris\/|CLDC\-|Mobi\/)/uis',$user_ag)){
return true;
};
};
return false;
}
I like JSON mainly because it's so terse. For web content that can be gzipped, this isn't necessarily a big deal (hence why xhtml is so popular). But there are occasions where this can be beneficial.
For example, for one project I was transmitting information that needed to be serialized and transmitted via XMPP. Since most servers will limit the amount of data you can transmit in a single message, I found it helpful to use JSON over the obvious alternative, XML.
As an added bonus, if you're familiar with Python or Javascript, you already pretty much know JSON and can interpret it without much training at all.
Here is another workaround with refernce to JavierFuentes answer:
<a [routerLink]="['self-route', id]" fragment="some-element" (click)="gotoHashtag('some-element')">Jump to Element</a>
in script:
import {ActivatedRoute} from "@angular/router";
import {Subscription} from "rxjs/Subscription";
export class Links {
private scrollExecuted: boolean = false;
constructor(private route: ActivatedRoute) {}
ngAfterViewChecked() {
if (!this.scrollExecuted) {
let routeFragmentSubscription: Subscription;
routeFragmentSubscription = this.route.fragment.subscribe(fragment => {
if (fragment) {
let element = document.getElementById(fragment);
if (element) {
element.scrollIntoView();
this.scrollExecuted = true;
// Free resources
setTimeout(
() => {
console.log('routeFragmentSubscription unsubscribe');
routeFragmentSubscription.unsubscribe();
}, 0);
}
}
});
}
}
gotoHashtag(fragment: string) {
const element = document.querySelector("#" + fragment);
if (element) element.scrollIntoView(element);
}
}
This allows user to directly scroll to element, if user directly lands on the page having hashtag in url.
But in this case, I have subscribed route Fragment in ngAfterViewChecked
but ngAfterViewChecked()
gets called continuously per every ngDoCheck
and it doesn't allows user to scroll back to top, so routeFragmentSubscription.unsubscribe
is called after a timeout of 0 millis after view is scrolled to element.
Additionally gotoHashtag
method is defined to scroll to element when user specifically clicks on the anchor tag.
Update:
If url has querystrings, [routerLink]="['self-route', id]"
in anchor wont preserve the querystrings. I tried following workaround for the same:
<a (click)="gotoHashtag('some-element')">Jump to Element</a>
constructor( private route: ActivatedRoute,
private _router:Router) {
}
...
...
gotoHashtag(fragment: string) {
let url = '';
let urlWithSegments = this._router.url.split('#');
if(urlWithSegments.length){
url = urlWithSegments[0];
}
window.location.hash = fragment;
const element = document.querySelector("#" + fragment);
if (element) element.scrollIntoView(element);
}
Global are good when it comes to configuration . When we want our configuration/changes to have a global impact on entire project.
So we can change one configuration and the changes are directed to entire project . But I must warn you would have to be very smart to use globals .
Actually, using ZSH allows you to use special mapping of environment variables. So you can simply do:
# append
path+=('/home/david/pear/bin')
# or prepend
path=('/home/david/pear/bin' $path)
# export to sub-processes (make it inherited by child processes)
export PATH
For me that's a very neat feature which can be propagated to other variables. Example:
typeset -T LD_LIBRARY_PATH ld_library_path :
To update Angular CLI to a new version, you must update both the global package and your project's local package.
Global package:
npm uninstall -g @angular/cli
npm cache clean
# if npm version is > 5 then use `npm cache verify` to avoid errors (or to avoid using --force)
npm install -g @angular/cli@latest
Local project package:
rm -rf node_modules dist # use rmdir /S/Q node_modules dist in Windows Command Prompt; use rm -r -fo node_modules,dist in Windows PowerShell
npm install --save-dev @angular/cli@latest
npm install
Source: Github
I like Jon Skeet's answer, but would like to add one thing. I'm not sure if Jon was expecting the ctor to always be passed in the Local timezone. But I want to use it for cases where it's something other then local.
I'm reading values from a database, and I know what timezone that database is in. So in the ctor, I'll pass in the timezone of the database. But then I would like the value in local time. Jon's LocalTime does not return the original date converted into a local timezone date. It returns the date converted into the original timezone (whatever you had passed into the ctor).
I think these property names clear it up...
public DateTime TimeInOriginalZone { get { return TimeZoneInfo.ConvertTime(utcDateTime, timeZone); } }
public DateTime TimeInLocalZone { get { return TimeZoneInfo.ConvertTime(utcDateTime, TimeZoneInfo.Local); } }
public DateTime TimeInSpecificZone(TimeZoneInfo tz)
{
return TimeZoneInfo.ConvertTime(utcDateTime, tz);
}
Try placing $PATH at the end.
export PATH=/usr/local/git/bin:/usr/local/bin:$PATH
it really depends on how many boarder use in your view , sometimes , just add a UIVIEW which the size is a bit bigger to create the border . the method is faster than produce a view
The real problem here is that there is a bug in hibernate where it uses select-list aliases in the where-clause:
http://opensource.atlassian.com/projects/hibernate/browse/HHH-817
Just in case someone lands here looking for answers, go look at the ticket. It took 5 years to fix but in theory it'll be in one of the next releases and then I suspect your issue will go away.
Here's one I just put together that works for me. It will return an array with 2 elements. The first element is everything before the ? and the second is an array containing all of the query string variables in an associative array.
function disectURL()
{
$arr = array();
$a = explode('?',sprintf(
"%s://%s%s",
isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off' ? 'https' : 'http',
$_SERVER['SERVER_NAME'],
$_SERVER['REQUEST_URI']
));
$arr['base_url'] = $a[0];
$arr['query_string'] = [];
if(sizeof($a) == 2)
{
$b = explode('&', $a[1]);
$qs = array();
foreach ($b as $c)
{
$d = explode('=', $c);
$qs[$d[0]] = $d[1];
}
$arr['query_string'] = (count($qs)) ? $qs : '';
}
return $arr;
}
Note: This is an expansion of the answer provided by macek above. (Credit where credit is due.)
Eclipse Oxygen - after installation of Lombok according to the process described on the Lombok page, still could not use @Log annotation.
Solution : Project --> Properties - Enable annotation processing
long a = 1111;
Long b = new Long(1113);
System.out.println(b.equals(a) ? "equal" : "different");
System.out.println((long) b == a ? "equal" : "different");
Here you go:
public class DemoDate {
public static void main(String[] args) {
LocalDate today = LocalDate.now();
System.out.println("Current date: " + today);
//add 1 month to the current date
LocalDate date2 = today.plus(1, ChronoUnit.MONTHS);
System.out.println("Next month: " + date2);
// Put latest date 1st and old date 2nd in 'between' method to get -ve date difference
long daysNegative = ChronoUnit.DAYS.between(date2, today);
System.out.println("Days : "+daysNegative);
// Put old date 1st and new date 2nd in 'between' method to get +ve date difference
long datePositive = ChronoUnit.DAYS.between(today, date2);
System.out.println("Days : "+datePositive);
}
}
Very easy to use extension for UIView, editable directly from storyboard. Swift 4+
@IBDesignable extension UIView {
@IBInspectable var shadowColor: UIColor?{
set {
guard let uiColor = newValue else { return }
layer.shadowColor = uiColor.cgColor
}
get{
guard let color = layer.shadowColor else { return nil }
return UIColor(cgColor: color)
}
}
@IBInspectable var shadowOpacity: Float{
set {
layer.shadowOpacity = newValue
}
get{
return layer.shadowOpacity
}
}
@IBInspectable var shadowOffset: CGSize{
set {
layer.shadowOffset = newValue
}
get{
return layer.shadowOffset
}
}
@IBInspectable var shadowRadius: CGFloat{
set {
layer.shadowRadius = newValue
}
get{
return layer.shadowRadius
}
}
}
This should work:
start "" "c:\program files\php\php.exe" D:\mydocs\mp\index.php param1 param2
The start
command interprets the first argument as a window title if it contains spaces. In this case, that means start
considers your whole argument a title and sees no command. Passing ""
(an empty title) as the first argument to start
fixes the problem.
You can do it using FullscreenVideoView
class. Its a small library project. It's video progress dialog is build in. it's gradle is :
compile 'com.github.rtoshiro.fullscreenvideoview:fullscreenvideoview:1.1.0'
your VideoView xml is like this
<com.github.rtoshiro.view.video.FullscreenVideoLayout
android:id="@+id/videoview"
android:layout_width="match_parent"
android:layout_height="match_parent" />
In your activity , initialize it using this way:
FullscreenVideoLayout videoLayout;
videoLayout = (FullscreenVideoLayout) findViewById(R.id.videoview);
videoLayout.setActivity(this);
Uri videoUri = Uri.parse("YOUR_VIDEO_URL");
try {
videoLayout.setVideoURI(videoUri);
} catch (IOException e) {
e.printStackTrace();
}
That's it. Happy coding :)
If want to know more then visit here
Edit: gradle path has been updated. compile it now
compile 'com.github.rtoshiro.fullscreenvideoview:fullscreenvideoview:1.1.2'
The only thing that worked for me was modifying the call to suptitle:
fig.suptitle("title", y=.995)
I tried all the detailed steps by JaMIT and still got stumped by this error. After a good amount of head-banging, I figured it out. I was careless. You should be able to reproduce this painful-to-look-at error w/ the following sample code.
[jaswantp@jaswant-arch build]$ gcc -v
Using built-in specs.
COLLECT_GCC=gcc
COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-pc-linux-gnu/10.2.0/lto-wrapper
Target: x86_64-pc-linux-gnu
Configured with: /build/gcc/src/gcc/configure --prefix=/usr --libdir=/usr/lib --libexecdir=/usr/lib --mandir=/usr/share/man --infodir=/usr/share/info --with-bugurl=https://bugs.archlinux.org/ --enable-languages=c,c++,ada,fortran,go,lto,objc,obj-c++,d --with-isl --with-linker-hash-style=gnu --with-system-zlib --enable-__cxa_atexit --enable-cet=auto --enable-checking=release --enable-clocale=gnu --enable-default-pie --enable-default-ssp --enable-gnu-indirect-function --enable-gnu-unique-object --enable-install-libiberty --enable-linker-build-id --enable-lto --enable-multilib --enable-plugin --enable-shared --enable-threads=posix --disable-libssp --disable-libstdcxx-pch --disable-libunwind-exceptions --disable-werror gdc_include_dir=/usr/include/dlang/gdc
Thread model: posix
Supported LTO compression algorithms: zlib zstd
gcc version 10.2.0 (GCC)
// CelesetialBody.h
class CelestialBody{
public:
virtual void Print();
protected:
CelestialBody();
virtual ~CelestialBody();
};
// CelestialBody.cpp
#include "CelestialBody.h"
CelestialBody::CelestialBody() {}
CelestialBody::~CelestialBody() = default;
void CelestialBody::Print() {}
// Planet.h
#include "CelestialBody.h"
class Planet : public CelestialBody
{
public:
void Print() override;
protected:
Planet();
~Planet() override;
};
// Planet.cpp
#include "Planet.h"
Planet::Planet() {}
Planet::~Planet() {}
void Print() {} // Deliberately forgot to prefix `Planet::`
# CMakeLists.txt
cmake_minimum_required(VERSION 3.12)
project (space_engine)
add_library (CelestialBody SHARED CelestialBody.cpp)
add_library (Planet SHARED Planet.cpp)
target_include_directories (CelestialBody PRIVATE ${CMAKE_CURRENT_LIST_DIR})
target_include_directories (Planet PRIVATE ${CMAKE_CURRENT_LIST_DIR})
target_link_libraries (Planet PUBLIC CelestialBody)
# hardened linker flags to catch undefined symbols
target_link_options(Planet
PRIVATE
-Wl,--as-needed
-Wl,--no-undefined
)
And we get our favourite error.
$ mkdir build
$ cd build
$ cmake ..
$ make
[ 50%] Built target CelestialBody
Scanning dependencies of target Planet
[ 75%] Building CXX object CMakeFiles/Planet.dir/Planet.cpp.o
[100%] Linking CXX shared library libPlanet.so
/usr/bin/ld: CMakeFiles/Planet.dir/Planet.cpp.o: in function `Planet::Planet()':
Planet.cpp:(.text+0x1b): undefined reference to `vtable for Planet'
/usr/bin/ld: CMakeFiles/Planet.dir/Planet.cpp.o: in function `Planet::~Planet()':
Planet.cpp:(.text+0x3d): undefined reference to `vtable for Planet'
collect2: error: ld returned 1 exit status
make[2]: *** [CMakeFiles/Planet.dir/build.make:104: libPlanet.so] Error 1
make[1]: *** [CMakeFiles/Makefile2:97: CMakeFiles/Planet.dir/all] Error 2
make: *** [Makefile:103: all] Error 2
What I've done in Planet.cpp
should of course be resolved with this tip
- Look at your class definition. Find the first non-inline virtual function that is not pure virtual (not "= 0") and whose definition you provide (not "= default").
from JaMIT's answer.
If there is anyone else who tried all the above and nothing worked, maybe you too, like me, carelessly forgot to prefix <ClassName>::
to one or more member functions.
Either I need to get my eyes checked or I need to get some sleep.
Documentation is quite clear: https://docs.python.org/2/library/json.html
json.load(fp[, encoding[, cls[, object_hook[, parse_float[, parse_int[, parse_constant[, object_pairs_hook[, **kw]]]]]]]])
Deserialize fp (a .read()-supporting file-like object containing a JSON document) to a Python object using this conversion table.
json.loads(s[, encoding[, cls[, object_hook[, parse_float[, parse_int[, parse_constant[, object_pairs_hook[, **kw]]]]]]]])
Deserialize s (a str or unicode instance containing a JSON document) to a Python object using this conversion table.
So load
is for a file, loads
for a string
Similar to @Akash but here is another approach that I've used. It uses str
than lambda
because python lambda
always gives me an alien-feelings.
import argparse
from distutils.util import strtobool
parser = argparse.ArgumentParser()
parser.add_argument("--my_bool", type=str, default="False")
args = parser.parse_args()
if bool(strtobool(args.my_bool)) is True:
print("OK")
I have also faced this problem and the solution is:
I added this code again and my program ran accurately:
Application.Run(new PayrollSystem());
//File name this code removed by me accidentally.
Below is the code to do it in VTD-XML
import com.ximpleware.*;
public class queryAttr{
public static void main(String[] s) throws VTDException{
VTDGen vg= new VTDGen();
if (!vg.parseFile("input.xml", false))
return false;
VTDNav vn = vg.getNav();
AutoPilot ap = new AutoPilot(vn);
ap.selectXPath("//xml/ep/source/@type");
int i=0;
while((i = ap.evalXPath())!=-1){
system.out.println(" attr val ===>"+ vn.toString(i+1));
}
}
}
If you want to insert this formula =SUMIFS(B2:B10,A2:A10,F2)
into cell G2, here is how I did it.
Range("G2")="=sumifs(B2:B10,A2:A10," & _
"F2)"
To split a line of code, add an ampersand, space and underscore.
This worked for me
textview.setTypeface(textview.getTypeface(), Typeface.BOLD);
or
textview.setTypeface(Typeface.DEFAULT_BOLD);
The Perl loop in the question reads from all the file name arguments on the command line, or from standard input if no files are specified. The answers I see all seem to process a single file or standard input if there is no file specified.
Although often derided accurately as UUOC (Useless Use of cat
), there are times when cat
is the best tool for the job, and it is arguable that this is one of them:
cat "$@" |
while read -r line
do
echo "$line"
done
The only downside to this is that it creates a pipeline running in a sub-shell, so things like variable assignments in the while
loop are not accessible outside the pipeline. The bash
way around that is Process Substitution:
while read -r line
do
echo "$line"
done < <(cat "$@")
This leaves the while
loop running in the main shell, so variables set in the loop are accessible outside the loop.
For me a Git repository (not GitHub) was already created, but empty. This was my solution for adding the existing project to the Git repository:
.gitignore
file.It would be interesting to see this all done directly in Visual Studio 2015 without tools like Git Extensions, but the things I tried in Visual Studio didn't work (Add to source control is not available for my project, adding a remote didn't help, etc.).
When encountering an 'Unsupported feature' error while using Statement.RETURN_GENERATED_KEYS
, try this:
String[] returnId = { "BATCHID" };
String sql = "INSERT INTO BATCH (BATCHNAME) VALUES ('aaaaaaa')";
PreparedStatement statement = connection.prepareStatement(sql, returnId);
int affectedRows = statement.executeUpdate();
if (affectedRows == 0) {
throw new SQLException("Creating user failed, no rows affected.");
}
try (ResultSet rs = statement.getGeneratedKeys()) {
if (rs.next()) {
System.out.println(rs.getInt(1));
}
rs.close();
}
Where BATCHID
is the auto generated id.
You mention Haxe/NME but you seem to instinctively dislike it. However, my experience with it has been very positive. Sure, the API is a reimplementation of the Flash API, but you're not limited to targeting Flash, you can also compile to HTML5 or native Windows, Mac, iOS and Android apps. Haxe is a pleasant, modern language similar to Java or C#.
If you're interested, I've written a bit about my experience using Haxe/NME: link
Consider building an Add-on that has an actual button and not using the outdated method of linking an image to a script function.
In the script editor, under the Help menu >> Welcome Screen >> link to Google Sheets Add-on - will give you sample code to use.
As already mentioned you have to use DateFormatter to format your Date objects. The easiest way to do it is creating a read-only computed property Date extension.
Read-Only Computed Properties
A computed property with a getter but no setter is known as a read-only computed property. A read-only computed property always returns a value, and can be accessed through dot syntax, but cannot be set to a different value.
Note:
You must declare computed properties—including read-only computed properties—as variable properties with the var keyword, because their value is not fixed. The let keyword is only used for constant properties, to indicate that their values cannot be changed once they are set as part of instance initialization.
You can simplify the declaration of a read-only computed property by removing the get keyword and its braces:
extension Formatter {
static let date = DateFormatter()
}
extension Date {
var europeanFormattedEn_US : String {
Formatter.date.calendar = Calendar(identifier: .iso8601)
Formatter.date.locale = Locale(identifier: "en_US_POSIX")
Formatter.date.timeZone = .current
Formatter.date.dateFormat = "dd/M/yyyy, H:mm"
return Formatter.date.string(from: self)
}
}
To convert it back you can create another read-only computed property but as a string extension:
extension String {
var date: Date? {
return Formatter.date.date(from: self)
}
func dateFormatted(with dateFormat: String = "dd/M/yyyy, H:mm", calendar: Calendar = Calendar(identifier: .iso8601), defaultDate: Date? = nil, locale: Locale = Locale(identifier: "en_US_POSIX"), timeZone: TimeZone = .current) -> Date? {
Formatter.date.calendar = calendar
Formatter.date.defaultDate = defaultDate ?? calendar.date(bySettingHour: 12, minute: 0, second: 0, of: Date())
Formatter.date.locale = locale
Formatter.date.timeZone = timeZone
Formatter.date.dateFormat = dateFormat
return Formatter.date.date(from: self)
}
}
Usage:
let dateFormatted = Date().europeanFormattedEn_US //"29/9/2018, 16:16"
if let date = dateFormatted.date {
print(date.description(with:.current)) // Saturday, September 29, 2018 at 4:16:00 PM Brasilia Standard Time\n"\
date.europeanFormattedEn_US // "29/9/2018, 16:27"
}
let dateString = "14/7/2016"
if let date = dateString.toDateFormatted(with: "dd/M/yyyy") {
print(date.description(with: .current))
// Thursday, July 14, 2016 at 12:00:00 PM Brasilia Standard Time\n"
}
Try this:
<table class='borderless'>
.borderless {
border:none;
}
Note: What you were doing before was not working because your css code was targeting a table within your .borderless table (which probably didn't exist)
There are many ways to solve this. My preferred approach is to have interfaces:
public interface ICode {
/*your preferred code type here, can be int or string or whatever*/ id();
}
public interface IMessage {
ICode code();
}
Now you can define any number of enums which provide messages:
public enum DatabaseMessage implements IMessage {
CONNECTION_FAILURE(DatabaseCode.CONNECTION_FAILURE, ...);
}
Now you have several options to turn those into Strings. You can compile the strings into your code (using annotations or enum constructor parameters) or you can read them from a config/property file or from a database table or a mixture. The latter is my preferred approach because you will always need some messages that you can turn into text very early (ie. while you connect to the database or read the config).
I'm using unit tests and reflection frameworks to find all types that implement my interfaces to make sure each code is used somewhere and that the config files contain all expected messages, etc.
Using frameworks that can parse Java like https://github.com/javaparser/javaparser or the one from Eclipse, you can even check where the enums are used and find unused ones.
From the documentation:
The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased
It really depends on your particular requirements, there's no "rule of thumb" for specifying an initial load factor.
You can set the figure size if you explicitly create the figure with
plt.figure(figsize=(3,4))
You need to set figure size before calling plt.plot()
To change the format of the saved figure just change the extension in the file name. However, I don't know if any of matplotlib backends support tiff
Check the status of the new build on the "Activity" tab. Once the "Processing" label disappears from the build you should be able to use it.
A process normally has two outputs to screen: stdout (standard out), and stderr (standard error).
Normally informational messages go to sdout
, and errors and alerts go to stderr
.
You can turn off stdout
for a command by doing
MyCommand >/dev/null
and turn off stderr
by doing:
MyCommand 2>/dev/null
If you want both off, you can do:
MyCommand 2>&1 >/dev/null
The 2>&1
says send stderr to the same place as stdout.
GET requests can have "Accept" headers, which say which types of content the client understands. The server can then use that to decide which content type to send back.
They're optional though.
http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1
Try this:
import tkinter as tk
from PIL import ImageTk, Image
#This creates the main window of an application
window = tk.Tk()
window.title("Join")
window.geometry("300x300")
window.configure(background='grey')
path = "Aaron.jpg"
#Creates a Tkinter-compatible photo image, which can be used everywhere Tkinter expects an image object.
img = ImageTk.PhotoImage(Image.open(path))
#The Label widget is a standard Tkinter widget used to display a text or image on the screen.
panel = tk.Label(window, image = img)
#The Pack geometry manager packs widgets in rows or columns.
panel.pack(side = "bottom", fill = "both", expand = "yes")
#Start the GUI
window.mainloop()
Related docs: ImageTk Module, Tkinter Label Widget, Tkinter Pack Geometry Manager
The way I can think of without using any built-in functions:
a = 'word'
count = 0
for letter in a:
count += 1
b = ''
for letter in a:
b += a[count-1]
count -= 1
And if you print b:
print b
drow
I had the same problem and while searching I came across this question, and after I found a good solution for me, I would like to share it with you guys in case some one can benefit from it.
Here it is:
<select class="place_holder dropdown">
<option selected="selected" style=" display: none;">Sort by</option>
<option>two</option>
<option>something</option>
<option>4</option>
<option>5</option>
</select>
.place_holder {
color: gray;
}
option {
color: #000000;
}
jQuery(".dropdown").change(function () {
jQuery(this).removeClass("place_holder");
});
After the customer makes the first select, there isn't any need for gray color, so the JavaScript code removes the class place_holder
.
Thanks to @user1096901, as a workaround for the Internet Explorer browser, you can add the place_holder
class again in case the first option is selected again :)
Kind of both. Firstly java compiled(some would prefer to say "translated") to bytecode, which then either compiled, or interpreted depending on mood of JIT.
sed
can perform text transformations on input stream from a file or from a pipeline. Example:
echo 'C:\foo\bar.xml' | sed 's/\\/\//g'
gets
C:/foo/bar.xml
You can use mbstring:
$text = mb_convert_encoding($text, 'UTF-8', 'UTF-8');
...will remove invalid characters.
See: Replacing invalid UTF-8 characters by question marks, mbstring.substitute_character seems ignored
Depending on your Color Model, there are different methods to create a darker (shaded) or lighter (tinted) color:
RGB
:
To shade:
newR = currentR * (1 - shade_factor)
newG = currentG * (1 - shade_factor)
newB = currentB * (1 - shade_factor)
To tint:
newR = currentR + (255 - currentR) * tint_factor
newG = currentG + (255 - currentG) * tint_factor
newB = currentB + (255 - currentB) * tint_factor
More generally, the color resulting in layering a color RGB(currentR,currentG,currentB)
with a color RGBA(aR,aG,aB,alpha)
is:
newR = currentR + (aR - currentR) * alpha
newG = currentG + (aG - currentG) * alpha
newB = currentB + (aB - currentB) * alpha
where (aR,aG,aB) = black = (0,0,0)
for shading, and (aR,aG,aB) = white = (255,255,255)
for tinting
HSV
or HSB
:
Value
/ Brightness
or increase the Saturation
Saturation
or increase the Value
/ Brightness
HSL
:
Lightness
Lightness
There exists formulas to convert from one color model to another. As per your initial question, if you are in RGB
and want to use the HSV
model to shade for example, you can just convert to HSV
, do the shading and convert back to RGB
. Formula to convert are not trivial but can be found on the internet. Depending on your language, it might also be available as a core function :
RGB
has the advantage of being really simple to implement, but:
HSV
or HSB
is kind of complex because you need to play with two parameters to get what you want (Saturation
& Value
/ Brightness
)HSL
is the best from my point of view:
50%
means an unaltered Hue>50%
means the Hue is lighter (tint)<50%
means the Hue is darker (shade)Lightness
part)Since the jar file 'executes' then it contains compiled java files known as .class files. You cannot import it to eclipse and modify the code. You should ask the supplier of the "demo" for the "source code". (or check the page you got the demo from for the source code)
Unless, you want to decompile the .class files and import to Eclipse. That may not be the case for starters.
If you can add an annotation to the source file, an annotation processor or code generator like this one can be used.
import net.zerobuilder.BeanBuilder
@BeanBuilder
public class DummyBean {
// bean stuff
}
A class DummyBeanBuilders
will be generates, which has a static method dummyBeanUpdater
to create shallow copies, the same way as you would do it manually.
DummyBean bean = new DummyBean();
// Call some setters ...
// Now make a copy
DummyBean copy = DummyBeanBuilders.dummyBeanUpdater(bean).done();
To loop from current record to the end:
While Me.CurrentRecord < Me.Recordset.RecordCount
' ... do something to current record
' ...
DoCmd.GoToRecord Record:=acNext
Wend
To check if it is possible to go to next record:
If Me.CurrentRecord < Me.Recordset.RecordCount Then
' ...
End If
Its easy, dont Align it to anything
<Button_x000D_
android:id="@+id/the_button"_x000D_
android:layout_width="wrap_content"_x000D_
android:layout_height="wrap_content" _x000D_
android:layout_centerInParent="true"_x000D_
android:text="Centered Button"/>
_x000D_
Keep it simple
replace VARIABLE_KEY with the key of the variable to get its value
var get_value = window.location.href.match(/(?<=VARIABLE_KEY=)(.*?)[^&]+/)[0];
If you are using jQuery then:
HTML:
<a id="openMap" href="/map/">link</a>
JS:
$(document).ready(function() {
$("#openMap").click(function(){
popup('/map/', 300, 300, 'map');
return false;
});
});
This has the benefit of still working without JS, or if the user middle clicks the link.
It also means that I could handle generic popups by rewriting again to:
HTML:
<a class="popup" href="/map/">link</a>
JS:
$(document).ready(function() {
$(".popup").click(function(){
popup($(this).attr("href"), 300, 300, 'map');
return false;
});
});
This would let you add a popup to any link by just giving it the popup class.
This idea could be extended even further like so:
HTML:
<a class="popup" data-width="300" data-height="300" href="/map/">link</a>
JS:
$(document).ready(function() {
$(".popup").click(function(){
popup($(this).attr("href"), $(this).data('width'), $(this).data('height'), 'map');
return false;
});
});
I can now use the same bit of code for lots of popups on my whole site without having to write loads of onclick stuff! Yay for reusability!
It also means that if later on I decide that popups are bad practice, (which they are!) and that I want to replace them with a lightbox style modal window, I can change:
popup($(this).attr("href"), $(this).data('width'), $(this).data('height'), 'map');
to
myAmazingModalWindow($(this).attr("href"), $(this).data('width'), $(this).data('height'), 'map');
and all my popups on my whole site are now working totally differently. I could even do feature detection to decide what to do on a popup, or store a users preference to allow them or not. With the inline onclick, this requires a huge copy and pasting effort.
Visual C++ string functions supporting unicode: http://msdn.microsoft.com/en-us/library/cc194799.aspx
the one you are probably looking for is _wcsnicmp
For end of line use:
git diff --ignore-space-at-eol
Instead of what are you using currently:
git diff -w (--ignore-all-space)
For start of line... you are out of luck if you want a built in solution.
However, if you don't mind getting your hands dirty there's a rather old patch floating out there somewhere that adds support for "--ignore-space-at-sol".
If you are using bootstrap or any other 3rd party CSS, make sure you specify the media screen only on it, so you have the control of the print media type in your own CSS files:
<link rel="stylesheet" media="screen" href="">
_x000D_
tr
can be more concise for removing characters than sed
or awk
, especially when you want to remove different characters from a string.
Removing double quotes:
echo '"Hi"' | tr -d \"
# Produces Hi without quotes
Removing different kinds of brackets:
echo '[{Hi}]' | tr -d {}[]
# Produces Hi without brackets
-d
stands for "delete".
none of above worked for me , i updated the appCompat - v7 version in my app gradle file from 23 to 25.3.1. helped to make it work for me
The where
statement gets executed before the order by
. So, your desired query is saying "take the first row and then order it by t_stamp
desc". And that is not what you intend.
The subquery method is the proper method for doing this in Oracle.
If you want a version that works in both servers, you can use:
select ril.*
from (select ril.*, row_number() over (order by t_stamp desc) as seqnum
from raceway_input_labo ril
) ril
where seqnum = 1
The outer *
will return "1" in the last column. You would need to list the columns individually to avoid this.
Your best bet would be to anticipate prefixes, so:
"(|(displayName=SEARCHKEY*)(displayName=ITSM - SEARCHKEY*)(displayName=alt prefix - SEARCHKEY*))"
Clunky, but I'm doing a similar thing within my organization.
For anyone else finding this - its worth noting that you can set the key value in the input name. Thanks to the answer in POSTing Form Fields with same Name Attribute you also can interplay strings or integers without quoting.
The answers assume that you don't mind the key value coming back for PHP however you can set name=[yourval]
(string or int) which then allows you to refer to an existing record.
Not to reinvent the wheel, here is my favourite one-liner solution:
/**_x000D_
* Convert milliseconds to time string (hh:mm:ss:mss)._x000D_
*_x000D_
* @param Number ms_x000D_
*_x000D_
* @return String_x000D_
*/_x000D_
function time(ms) {_x000D_
return new Date(ms).toISOString().slice(11, -1);_x000D_
}_x000D_
_x000D_
console.log( time(12345 * 1000) ); // "03:25:45.000"
_x000D_
Method Date.prototype.toISOString()
returns a string in simplified extended ISO format (ISO 8601), which is always 24 characters long: YYYY-MM-DDTHH:mm:ss.sssZ
. This method is supported in all modern browsers (IE9+) and JavaScript engines.
UPDATE: The solution above is always limited to range of one day, which is fine if you use it to format milliseconds up to 24 hours (i.e. ms < 86400000
). To make it working with any input value, I have extended it into a nice universal prototype method:
/**_x000D_
* Convert (milli)seconds to time string (hh:mm:ss[:mss])._x000D_
*_x000D_
* @param Boolean isSec_x000D_
*_x000D_
* @return String_x000D_
*/_x000D_
Number.prototype.toTime = function(isSec) {_x000D_
var ms = isSec ? this * 1e3 : this,_x000D_
lm = ~(4 * !!isSec), /* limit fraction */_x000D_
fmt = new Date(ms).toISOString().slice(11, lm);_x000D_
_x000D_
if (ms >= 8.64e7) { /* >= 24 hours */_x000D_
var parts = fmt.split(/:(?=\d{2}:)/);_x000D_
parts[0] -= -24 * (ms / 8.64e7 | 0);_x000D_
return parts.join(':');_x000D_
}_x000D_
_x000D_
return fmt;_x000D_
};_x000D_
_x000D_
console.log( (12345 * 1000).toTime() ); // "03:25:45.000"_x000D_
console.log( (123456 * 789).toTime() ); // "27:03:26.784"_x000D_
console.log( 12345. .toTime(true) ); // "03:25:45"_x000D_
console.log( 123456789. .toTime(true) ); // "34293:33:09"
_x000D_
In my case build 1 was installed correctly in my mobile using the signed APK (also from Google Play Store). But when I update the application with build 2 for first time, I had an issue installing it with the signed APK as I got "There was a problem parsing the package".
I tried several methods as specified above. But did not work.
After some time, I rerun the commands
jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore my-key.keystore app-release-unsigned.apk myappkeyalias
zipalign -v 4 app-release-unsigned.apk MyApp.apk
and surprisingly, it worked.
It seems sometimes the APK built might be corrupt. So, Re-running jarsigner and zipalign commands resolved my issue.
Shared preferences introduced a getStringSet
and putStringSet
methods in API Level 11, but that's not compatible with older versions of Android (which are still popular), and also is limited to sets of strings.
Android does not provide better methods, and looping over maps and arrays for saving and loading them is not very easy and clean, specially for arrays. But a better implementation isn't that hard:
package com.example.utils;
import org.json.JSONObject;
import org.json.JSONArray;
import org.json.JSONException;
import android.content.Context;
import android.content.SharedPreferences;
public class JSONSharedPreferences {
private static final String PREFIX = "json";
public static void saveJSONObject(Context c, String prefName, String key, JSONObject object) {
SharedPreferences settings = c.getSharedPreferences(prefName, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString(JSONSharedPreferences.PREFIX+key, object.toString());
editor.commit();
}
public static void saveJSONArray(Context c, String prefName, String key, JSONArray array) {
SharedPreferences settings = c.getSharedPreferences(prefName, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString(JSONSharedPreferences.PREFIX+key, array.toString());
editor.commit();
}
public static JSONObject loadJSONObject(Context c, String prefName, String key) throws JSONException {
SharedPreferences settings = c.getSharedPreferences(prefName, 0);
return new JSONObject(settings.getString(JSONSharedPreferences.PREFIX+key, "{}"));
}
public static JSONArray loadJSONArray(Context c, String prefName, String key) throws JSONException {
SharedPreferences settings = c.getSharedPreferences(prefName, 0);
return new JSONArray(settings.getString(JSONSharedPreferences.PREFIX+key, "[]"));
}
public static void remove(Context c, String prefName, String key) {
SharedPreferences settings = c.getSharedPreferences(prefName, 0);
if (settings.contains(JSONSharedPreferences.PREFIX+key)) {
SharedPreferences.Editor editor = settings.edit();
editor.remove(JSONSharedPreferences.PREFIX+key);
editor.commit();
}
}
}
Now you can save any collection in shared preferences with this five methods. Working with JSONObject
and JSONArray
is very easy. You can use JSONArray (Collection copyFrom)
public constructor to make a JSONArray
out of any Java collection and use JSONArray
's get
methods to access the elements.
There is no size limit for shared preferences (besides device's storage limits), so these methods can work for most of usual cases where you want a quick and easy storage for some collection in your app. But JSON parsing happens here, and preferences in Android are stored as XMLs internally, so I recommend using other persistent data store mechanisms when you're dealing with megabytes of data.
"Fork" in this context means "Make a copy of their code so that I can add my own modifications". There's not much else to say. Every clone is essentially a fork, and it's up to the original to decide whether to pull the changes from the fork.
So, you want an 8-character wide field with spaces as the padding? Try "%8d". Here's a reference.
EDIT: What you're trying to do is not something that can be handled by printf alone, because it will not know what the longest number you are writing is. You will need to calculate the largest number before doing any printfs, and then figure out how many digits to use as the width of your field. Then you can use snprintf or similar to make a printf format on the spot.
char format[20];
snprintf(format, 19, "%%%dd\\n", max_length);
while (got_output) {
printf(format, number);
got_output = still_got_output();
}
You can do it programmatically:
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
int main() {
int fd = creat("/tmp/foo.txt", 0644);
ftruncate(fd, SIZE_IN_BYTES);
close(fd);
return 0;
}
This approach is especially useful to subsequently mmap the file into memory.
use the following command to check that the file has the correct size:
# du -B1 --apparent-size /tmp/foo.txt
Be careful:
# du /tmp/foo.txt
will probably print 0 because it is allocated as Sparse file if supported by your filesystem.
see also: man 2 open and man 2 truncate
JSDoc 3 allows you to annotate your functions with the @access private
(previously the @private
tag) which is also useful for broadcasting your intent to other developers - http://usejsdoc.org/tags-access.html
It's not enough to have just compile project("xy")
dependency.
You need to configure root project to include all modules (or to call them subprojects but that might not be correct word here).
Create a settings.gradle file in the root of your project and add this:
include ':progressfragment'
to that file. Then sync Gradle and it should work.
Also one interesting side note: If you add ':unexistingProject' in settings.gradle (project that you haven't created yet), Gradle will create folder for this project after sync (at least in Android studio this is how it behaves). So, to avoid errors with settings.gradle when you create project from existing files, first add that line to file, sync and then put existing code in created folder. Unwanted behavior arising from this might be that if you delete the project folder and then sync folder will come back empty because Gradle sync recreated it since it is still listed in settings.gradle.
I had the same problem. See if you are using hibernatesession.load()
. If so, try converting to hibernatesession.get()
. This solved my problem.
Watch this video, I had the same question. He shows you how to debug the service as well.
Here are his instructions using the basic C# Windows Service template in Visual Studio 2010/2012.
You add this to the Service1.cs file:
public void onDebug()
{
OnStart(null);
}
You change your Main() to call your service this way if you are in the DEBUG Active Solution Configuration.
static void Main()
{
#if DEBUG
//While debugging this section is used.
Service1 myService = new Service1();
myService.onDebug();
System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);
#else
//In Release this section is used. This is the "normal" way.
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new Service1()
};
ServiceBase.Run(ServicesToRun);
#endif
}
Keep in mind that while this is an awesome way to debug your service. It doesn't call OnStop()
unless you explicitly call it similar to the way we called OnStart(null)
in the onDebug()
function.
You should also use the style 'color' and not 'font-color'
<?php
foreach($months as $key => $month){
if(strpos($filename,$month)!==false){
echo "<style = 'color: #ff0000;'> Movie List for {$key} 2013 </style>";
}
}
?>
In general, the comments on double and single quotes are correct in other suggestions. $Variables only execute in double quotes.
Directory Services/LDAP lookups can be used to serve this purpose. It involves some changes at infrastructure level, but most production environments have such provision
There's nothing wrong with either version of your code. Whatever is causing this, that's not it.
Have you triple checked your locator? Your element definitely has name=submit not id=submit?
In case you just need to remove the duplicates using only ArrayList, no other Collection classes, then:-
//list is the original arraylist containing the duplicates as well
List<String> uniqueList = new ArrayList<String>();
for(int i=0;i<list.size();i++) {
if(!uniqueList.contains(list.get(i)))
uniqueList.add(list.get(i));
}
Hope this helps!
I think that this construct: if exists (select...
is specific for MS SQL. In MySQL EXISTS
predicate tells you whether the subquery finds any rows and it's used like this: SELECT column1 FROM t1 WHERE EXISTS (SELECT * FROM t2);
You can rewrite the above lines of code like this:
DELIMITER $$
CREATE PROCEDURE `checando`(in nombrecillo varchar(30), in contrilla varchar(30), out resultado int)
BEGIN
DECLARE count_prim INT;
DECLARE count_sec INT;
SELECT COUNT(*) INTO count_prim FROM compas WHERE nombre = nombrecillo AND contrasenia = contrilla;
SELECT COUNT(*) INTO count_sec FROM FROM compas WHERE nombre = nombrecillo;
if (count_prim > 0) then
set resultado = 0;
elseif (count_sec > 0) then
set resultado = -1;
else
set resultado = -2;
end if;
SELECT resultado;
END
I would use the following function. I don't like sprintf
; it doesn't do what I want!!
#define hexchar(x) ((((x)&0x0F)>9)?((x)+'A'-10):((x)+'0'))
typedef signed long long Int64;
// Special printf for numbers only
// See formatting information below.
//
// Print the number "n" in the given "base"
// using exactly "numDigits".
// Print +/- if signed flag "isSigned" is TRUE.
// Use the character specified in "padchar" to pad extra characters.
//
// Examples:
// sprintfNum(pszBuffer, 6, 10, 6, TRUE, ' ', 1234); --> " +1234"
// sprintfNum(pszBuffer, 6, 10, 6, FALSE, '0', 1234); --> "001234"
// sprintfNum(pszBuffer, 6, 16, 6, FALSE, '.', 0x5AA5); --> "..5AA5"
void sprintfNum(char *pszBuffer, int size, char base, char numDigits, char isSigned, char padchar, Int64 n)
{
char *ptr = pszBuffer;
if (!pszBuffer)
{
return;
}
char *p, buf[32];
unsigned long long x;
unsigned char count;
// Prepare negative number
if (isSigned && (n < 0))
{
x = -n;
}
else
{
x = n;
}
// Set up small string buffer
count = (numDigits-1) - (isSigned?1:0);
p = buf + sizeof (buf);
*--p = '\0';
// Force calculation of first digit
// (to prevent zero from not printing at all!!!)
*--p = (char)hexchar(x%base);
x = x / base;
// Calculate remaining digits
while(count--)
{
if(x != 0)
{
// Calculate next digit
*--p = (char)hexchar(x%base);
x /= base;
}
else
{
// No more digits left, pad out to desired length
*--p = padchar;
}
}
// Apply signed notation if requested
if (isSigned)
{
if (n < 0)
{
*--p = '-';
}
else if (n > 0)
{
*--p = '+';
}
else
{
*--p = ' ';
}
}
// Print the string right-justified
count = numDigits;
while (count--)
{
*ptr++ = *p++;
}
return;
}
Here is a UDF I built to detectc columns with extended ascii charaters. It is quick and you can extended the character set you want to check. The second parameter allows you to switch between checking anything outside the standard character set or allowing an extended set:
create function [dbo].[udf_ContainsNonASCIIChars]
(
@string nvarchar(4000),
@checkExtendedCharset bit
)
returns bit
as
begin
declare @pos int = 0;
declare @char varchar(1);
declare @return bit = 0;
while @pos < len(@string)
begin
select @char = substring(@string, @pos, 1)
if ascii(@char) < 32 or ascii(@char) > 126
begin
if @checkExtendedCharset = 1
begin
if ascii(@char) not in (9,124,130,138,142,146,150,154,158,160,170,176,180,181,183,184,185,186,192,193,194,195,196,197,199,200,201,202,203,204,205,206,207,209,210,211,212,213,214,216,217,218,219,220,221,223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,248,249,250,251,252,253,254,255)
begin
select @return = 1;
select @pos = (len(@string) + 1)
end
else
begin
select @pos = @pos + 1
end
end
else
begin
select @return = 1;
select @pos = (len(@string) + 1)
end
end
else
begin
select @pos = @pos + 1
end
end
return @return;
end
USAGE:
select Address1
from PropertyFile_English
where udf_ContainsNonASCIIChars(Address1, 1) = 1
Use Connection.isClosed()
function.
The JavaDoc states:
Retrieves whether this
Connection
object has been closed. A connection is closed if the method close has been called on it or if certain fatal errors have occurred. This method is guaranteed to returntrue
only when it is called after the method Connection.close has been called.
I had a similar problem but I came to a different solution that may help others. I used Spring Profiles to separate out test and app configuration classes.
Create a TestConfig class with a specific profile and exclude any app configuration from component scan you wish here.
In your test class set the profile to match the TestConfig and include it using the @ContextConfiguration annotation.
For example:
configuration:
@Profile("test")
@Configuration
@EnableWebMvc
@ComponentScan(
basePackages="your.base.package",
excludeFilters = {
@Filter(type = ASSIGNABLE_TYPE,
value = {
ExcludedAppConfig1.class,
ExcludedAppConfig2.class
})
})
public class TestConfig { ...}
test:
@ActiveProfiles("test")
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = TestConfig.class)
@WebAppConfiguration
public class SomeTest{ ... }
If you are sure id.substring(indexPos) is a number, you can do it like so:
var number = Number(id.substring(indexPos)) + 1;
Otherwise I suggest checking if the Number function evaluates correctly.
Agree completely with Bryan and others.
Instead, consider using multiple sections in your email that you can jump to using links and anchors (the 'a' tag). I think that you can emulate the behavior you want by including multiple copies of the text further down in your email. This is a bet messy though, so you could just have sets of anchors that link to each other and allow you to move back in forth between the 'summary' section and the 'expanded' one.
Example:
<a href="#section1">Jump to section!</a>
<p>A bunch of content</p>
<h2 id="section1">An anchor!</h2>
Clicking on the first link will move focus to the sub-section.
Here is another way to separate your table header and table body:
thead th {
background-color: #006DCC;
color: white;
}
tbody td {
background-color: #EEEEEE;
}
Have a look at this example for separation of head and body of table. JsFiddleLink
To make it work, I installed latex, typical latex extra, and pandoc.
With ubuntu:
sudo apt-get install texlive texlive-latex-extra pandoc
it takes some times: several 100 Mb to download. I read somewhere that you can use --no-install-recommends
for texlive and extra to reduce to the dl.
CreateImage(size, depth, channels)
https://opencv.willowgarage.com/documentation/python/core_operations_on_arrays.html#CreateImage
Just remove .metadata from your eclipse workspace You can find it C:\Users\username\workspace
var findObjectByLabel = function(objs, label) {
if(objs.label === label) {
return objs;
}
else{
if(objs.subs){
for(var i in objs.subs){
let found = findObjectByLabel(objs.subs[i],label)
if(found) return found
}
}
}
};
findObjectByLabel(cars, "Ford");