Google Maps basics
Zoom Level - zoom
0 - 19
0 lowest zoom (whole world)
19 highest zoom (individual buildings, if available) Retrieve current zoom level using mapObject.getZoom()
Java 8's String.join
provides a tidy way to do this in conjunction with Collections.nCopies
:
// say hello 100 times
System.out.println(String.join("", Collections.nCopies(100, "hello")));
Try the <wbr>
tag - not as elegant as the word-wrap
property that others suggested, but it's a working solution until all major browsers (read IE) implement CSS3.
I prefer to this approach because you can return the promise and use .then(successFunction, failFunction); anywhere you need to.
var promise = $.ajax({
type: 'GET',
dataType: 'json',
url: url,
timeout: 5000
}).then(function( data, textStatus, jqXHR ) {
alert('request successful');
}, function( jqXHR, textStatus, errorThrown ) {
alert('request failed');
});
//also access the success and fail using variable
promise.then(successFunction, failFunction);
You can look at the HEAD pointer (stored in .git/HEAD
) to see the sha1 of the currently checked-out commit, or it will be of the format ref: refs/heads/foo
for example if you have a local ref foo
checked out.
EDIT: If you'd like to do this from a shell, git symbolic-ref HEAD
will give you the same information.
In your example propertyInfo.GetValue(this, null)
should work. Consider altering GetNamesAndTypesAndValues()
as follows:
public void GetNamesAndTypesAndValues()
{
foreach (PropertyInfo propertyInfo in allClassProperties)
{
Console.WriteLine("{0} [type = {1}] [value = {2}]",
propertyInfo.Name,
propertyInfo.PropertyType,
propertyInfo.GetValue(this, null));
}
}
First try to downgrade your angular version using "ng add @angular/material7.3..0" after that check if the error is gone in my case it is gone after that use this ng update @angular/material in case you are using angular 9 or 10 you have to write code like this import {MatInputModule} from 'angular/material/input' Hope it will work for you
This is what I am going to use based on marc_s answer:
SELECT
SUBSTRING(DATA.value('(/PAGECONTENT/TEXT)[1]', 'VARCHAR(100)'),PATINDEX('%NORTH%',DATA.value('(/PAGECONTENT/TEXT)[1]', 'VARCHAR(100)')) - 20,999)
FROM WEBPAGECONTENT
WHERE COALESCE(PATINDEX('%NORTH%',DATA.value('(/PAGECONTENT/TEXT)[1]', 'VARCHAR(100)')),0) > 0
Return a substring on the search where the search criteria exists
UPDATE table_name SET
destination_column_name=orig_column_name
WHERE condition_if_necessary
I just watched the 30 minute Unity Dependency Injection IoC Screencast by David Hayden and felt that was a good explaination with examples. Here is a snippet from the show notes:
The screencast shows several common usages of the Unity IoC, such as:
Thanks for the earlier reply.
I figured out the solutions using selenium 2.0 classes.
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.ie.InternetExplorerDriver;
public class WebTableExample
{
public static void main(String[] args)
{
WebDriver driver = new InternetExplorerDriver();
driver.get("http://localhost/test/test.html");
WebElement table_element = driver.findElement(By.id("testTable"));
List<WebElement> tr_collection=table_element.findElements(By.xpath("id('testTable')/tbody/tr"));
System.out.println("NUMBER OF ROWS IN THIS TABLE = "+tr_collection.size());
int row_num,col_num;
row_num=1;
for(WebElement trElement : tr_collection)
{
List<WebElement> td_collection=trElement.findElements(By.xpath("td"));
System.out.println("NUMBER OF COLUMNS="+td_collection.size());
col_num=1;
for(WebElement tdElement : td_collection)
{
System.out.println("row # "+row_num+", col # "+col_num+ "text="+tdElement.getText());
col_num++;
}
row_num++;
}
}
}
This worked for me .
I am taking Stephen Grider's React Native on Udemy and one of the students posted this in Lecture 50. Pasted verbatim in the command line (w/o '$' of course).
$ export "ANDROID_HOME=/usr/local/opt/android-sdk" >~/.bash_profile
Try this.
view.animate()
.translationY(0)
.alpha(0.0f)
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
view.setVisibility(View.GONE);
}
});
Here is my UIImage crop implementation which obeys the imageOrientation property. All orientations were thoroughly tested.
inline double rad(double deg)
{
return deg / 180.0 * M_PI;
}
UIImage* UIImageCrop(UIImage* img, CGRect rect)
{
CGAffineTransform rectTransform;
switch (img.imageOrientation)
{
case UIImageOrientationLeft:
rectTransform = CGAffineTransformTranslate(CGAffineTransformMakeRotation(rad(90)), 0, -img.size.height);
break;
case UIImageOrientationRight:
rectTransform = CGAffineTransformTranslate(CGAffineTransformMakeRotation(rad(-90)), -img.size.width, 0);
break;
case UIImageOrientationDown:
rectTransform = CGAffineTransformTranslate(CGAffineTransformMakeRotation(rad(-180)), -img.size.width, -img.size.height);
break;
default:
rectTransform = CGAffineTransformIdentity;
};
rectTransform = CGAffineTransformScale(rectTransform, img.scale, img.scale);
CGImageRef imageRef = CGImageCreateWithImageInRect([img CGImage], CGRectApplyAffineTransform(rect, rectTransform));
UIImage *result = [UIImage imageWithCGImage:imageRef scale:img.scale orientation:img.imageOrientation];
CGImageRelease(imageRef);
return result;
}
It's because the CPU doesn't have so many cache misses (where it has to wait for the array data to come from the RAM chips). It would be interesting for you to adjust the size of the arrays continually so that you exceed the sizes of the level 1 cache (L1), and then the level 2 cache (L2), of your CPU and plot the time taken for your code to execute against the sizes of the arrays. The graph shouldn't be a straight line like you'd expect.
When I want to tidy up an array like this I use:
["Kathmandu", "Pokhara", "", "Dharan", "Butwal"] - ["", nil]
This will remove all blank or nil elements.
I just wanted to add these from TLDP:
~:$ echo $SHELL
/bin/bash
~:$ echo ${#SHELL}
9
~:$ ARRAY=(one two three)
~:$ echo ${#ARRAY}
3
~:$ echo ${TEST:-test}
test
~:$ echo $TEST
~:$ export TEST=a_string
~:$ echo ${TEST:-test}
a_string
~:$ echo ${TEST2:-$TEST}
a_string
~:$ echo $TEST2
~:$ echo ${TEST2:=$TEST}
a_string
~:$ echo $TEST2
a_string
~:$ export STRING="thisisaverylongname"
~:$ echo ${STRING:4}
isaverylongname
~:$ echo ${STRING:6:5}
avery
~:$ echo ${ARRAY[*]}
one two one three one four
~:$ echo ${ARRAY[*]#one}
two three four
~:$ echo ${ARRAY[*]#t}
one wo one hree one four
~:$ echo ${ARRAY[*]#t*}
one wo one hree one four
~:$ echo ${ARRAY[*]##t*}
one one one four
~:$ echo $STRING
thisisaverylongname
~:$ echo ${STRING%name}
thisisaverylong
~:$ echo ${STRING/name/string}
thisisaverylongstring
You are setting self.name
to the string "get_thing"
, not the function get_thing
.
If you want self.name
to be a function, then you should set it to one:
setattr(self, 'name', self.get_thing)
However, that's completely unnecessary for your other code, because you could just call it directly:
value_returned = self.get_thing()
The JsonTools library is very complete. It can be found at Github.
Tangentially related and only useful in case you have no root access and manually extract Git from an RPM (with rpm2cpio) or other package (.deb, ..) into a subfolder. Typical use case: you try to use a newer version of Git over the outdated one on a corporate server.
If git clone fails with fatal: index-pack failed
without early EOF mention but instead a help message about usage: git index-pack
, there is a version mismatch and you need to run git with the --exec-path
parameter:
git --exec-path=path/to/subfoldered/git/usr/bin/git clone <repo>
In order to have this happen automatically, specify in your ~/.bashrc
:
export GIT_EXEC_PATH=path/to/subfoldered/git/usr/libexec
you can check the type. s3 has a special application/x-directory
bucket.objects({:delimiter=>"/", :prefix=>"f1/"}).each { |obj| p obj.object.content_type }
Recently I found this approach to writing logs in android, which I think is super awesome.
public static final boolean FORCED_LOGGING = true;
private static final int CALLER_STACK_INDEX = 3;
public static void showLogs(String message) {
if (FORCED_LOGGING) {
StackTraceElement caller = Thread.currentThread().getStackTrace()[CALLER_STACK_INDEX];
String fullClassName = caller.getClassName();
String className = fullClassName.substring(fullClassName.lastIndexOf('.') + 1);
String methodName = caller.getMethodName();
int lineNumber = caller.getLineNumber();
Log.i("*** " + className + "." + methodName + "():" + lineNumber + "\n" , message);
}
}
For others running into this without any of the above solutions working AND you have modified the default theme, you might want to check the highlight color for occurrences.
Preferences > General > Editors > Text Editors > Annotations
Then select Occurrences in the Annotation Types, and change the Color Box to something other than your background color in your editor. You can also change the Highlight to a outline box by Checking "Text as" and selecting "Box" from the drop-down box (which is easier to see various syntax colors then with the highlights)
CentOS (RHEL) 7, has changed the firewall to use firewall-cmd
which has a notion of zones which is like a Windows version of Public, Home, and Private networks. You should look here to figure out which one you think you should use. EL7 uses public
by default so that is what my examples below use.
You can check which zone you are using with firewall-cmd --list-all
and change it with firewall-cmd --set-default-zone=<zone>
.
You will then know what zone to allow a service (or port) on:
firewall-cmd --permanent --zone=<zone> --add-service=http
firewall-cmd --permanent --zone=<zone> --add-port=80/tcp
You can check if the port has actually be opened by running:
firewall-cmd --zone=<zone> --query-port=80/tcp
firewall-cmd --zone=<zone> --query-service=http
According to the documentation,
When making changes to the firewall settings in Permanent mode, your selection will only take effect when you reload the firewall or the system restarts.
You can reload the firewall settings with: firewall-cmd --reload
.
One thing that I found out (the hard way), is that you should have
$('#selectField').change(function(){
// some content ...
});
defined BEFORE you are using
$('#selectField').val(10).trigger('change');
or
$('#selectField').val(10).change();
Even after applying above defined project specific settings on IntelliJ as well as Eclipse, it was still failing for me !
what worked for me was addition of maven plugin with source and target with 1.8 setting in POM XML:
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.0.2</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<classpathPrefix>lib/</classpathPrefix>
<mainClass>com.abc.sparkcore.JavaWordCount</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>copy</id>
<phase>install</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/lib</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
I made some changes to dina's answer to avoid attempting to download/combine 1200 parts if there aren't that many.
I also found it helpful to sort by waterfall
in the network tab of chrome. This will sort by the time the files are downloaded, so when you are streaming a video the most recently downloaded parts will be at the top, making it easy to find the .ts
links.
#!/bin/bash
# Name of the containing folder
GROUP="My Videos"
# Example link: https://vids.net/ABCAED/AADDCDE/m3u8/AADDCDE/AADDCDE_0.ts
# Insert below as: https://vids.net/ABCAED/AADDCDE/m3u8/AADDCDE/AADDCDE
# INSERT LINKS TO VIDEOS HERE
LINK=(
'Title for the video link'
'https://vids.net/ABCAED/AADDCDE/m3u8/AADDCDE/AADDCDE'
'Title for the next video'
'https://vids.net/EECEADFE/EECEADFE/m3u8/EECEADFE/EECEADFE'
)
# ------------------------------------------------------------------------------
mkdir "$GROUP"
cd "$GROUP"
I=0
while [ $I -lt ${#LINK[@]} ]
do
# create folder for streaming media
TITLE=${LINK[$I]}
mkdir "$TITLE"
cd "$TITLE"
mkdir 'parts'
cd 'parts'
J=$((I + 1))
URL=${LINK[$J]}
I=$((I + 2))
DIR="${URL##*/}"
# download all streaming media parts
VID=-1
while [ $? -eq 0 ];
do
VID=$((VID + 1))
wget $URL'_'$VID.ts
done
# combine parts
COUNTER=0
while [ $COUNTER -lt $VID ]; do
echo $DIR'_'$COUNTER.ts | tr " " "\n" >> tslist
let COUNTER=COUNTER+1
done
while read line; do cat $line >> $TITLE.ts; done < tslist
rm -rf tslist
mv "$TITLE.ts" "../$TITLE.ts"
cd ..
rm -rf 'parts'
cd ..
done
As of 10. July 2017, the issue of Bootstrap 4 support with bootstrap-select
is still open. In the open issue, there are some ad-hoc solutions which you could try with your project.
Or you could use a library like Select2 and add a theme to match Bootstrap 4. Here is an example: Select 2 with Bootstrap 4 (disclaimer: I'm not the author of this blog post and I haven't verified if this still works with the all versions of Bootstrap 4).
Very simple was to renew your certificate. Go to your developer member centre and go to your Provisioning profile and see what are the certificate Active and InActive and select Inactive certificate and hit Edit button then hit generate button. Now your certificate successful renewal for another 1 year. Thanks
I use such way for NETWORK_PROVIDER but you can add and for GPS.
LocationManager locationManager;
In onCreate I put
isLocationEnabled();
if(!isLocationEnabled()) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle(R.string.network_not_enabled)
.setMessage(R.string.open_location_settings)
.setPositiveButton(R.string.yes,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
})
.setNegativeButton(R.string.cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
And method of checking
protected boolean isLocationEnabled(){
String le = Context.LOCATION_SERVICE;
locationManager = (LocationManager) getSystemService(le);
if(!locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){
return false;
} else {
return true;
}
}
Cardview
is a bit coy. I had list of colors in my structure and Model is like
class ModelColor : Serializable {
var id: Int? = 0
var title: String? = ""
var color: Int? = 0// HERE IS THE COLOR FIELD WE WILL USE
constructor(id: Int?, title: String?, color: Int?) {
this.id = id
this.title = title
this.color = color
}
}
load the model with color, last item on constructure taking from R.color
list.add(ModelColor(2, getString(R.string.orange), R.color.orange_500))
and finaly you can setBackgriundResource
cv_add_goal_choose_color.setBackgroundResource(color)
You need to apply DATE_FORMAT
in the SELECT
clause, not the WHERE
clause:
SELECT DATE_FORMAT(create_date, '%m/%d/%Y')
FROM mytable
WHERE create_date BETWEEN CURDATE() - INTERVAL 30 DAY AND CURDATE()
Also note that CURDATE()
returns only the DATE
portion of the date, so if you store create_date
as a DATETIME
with the time portion filled, this query will not select the today's records.
In this case, you'll need to use NOW
instead:
SELECT DATE_FORMAT(create_date, '%m/%d/%Y')
FROM mytable
WHERE create_date BETWEEN NOW() - INTERVAL 30 DAY AND NOW()
For almost all cases the normal list is the right choice. The arrays module is more like a thin wrapper over C arrays, which give you kind of strongly typed containers (see docs), with access to more C-like types such as signed/unsigned short or double, which are not part of the built-in types. I'd say use the arrays module only if you really need it, in all other cases stick with lists.
If you can use repeated letters, you can use the *
operator:
>>> 'a'*5
'aaaaa'
extension UITextField {
func setBottomBorder(color:String) {
self.borderStyle = UITextBorderStyle.None
let border = CALayer()
let width = CGFloat(1.0)
border.borderColor = UIColor(hexString: color)!.cgColor
border.frame = CGRect(x: 0, y: self.frame.size.height - width, width: self.frame.size.width, height: self.frame.size.height)
border.borderWidth = width
self.layer.addSublayer(border)
self.layer.masksToBounds = true
}
}
and then just do this:
yourTextField.setBottomBorder(color: "#3EFE46")
another way to find last highest data based on date
SELECT A.JID,A.EntryDate,RefundDate,Comments,Refund, ActionBy FROM (
(select JID, Max(EntryDate) AS EntryDate from refundrequested GROUP BY JID) A
Inner JOIN (SELECT JID,ENTRYDATE,refundDate,Comments,refund,ActionBy from refundrequested) B
ON A.JID=B.JID AND A.EntryDate = B.EntryDate)
There doesn't seem to be a standardized default value. I have the feeling the default is 0
, and the timeout event left totally dependent on browser and network settings.
For IE, there is a timeout property for XMLHTTPRequests here. It defaults to null, and it says the network stack is likely to be the first to time out (which will not generate an ontimeout event by the way).
One way would be to create an ObservableCollection (System.Collections.ObjectModel) and have your dictionary data in there. Then you should be able to bind the ObservableCollection to your ListBox.
In your XAML you should have something like this:
<ListBox ItemsSource="{Binding Path=Name_of_your_ObservableCollection" />
I had the same problem (JUnit tests failed in Maven Surefire but passed in Eclipse) and managed to solve it by setting forkMode to always in the maven surefire configuration in pom.xml:
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.12</version> <configuration> <forkMode>always</forkMode> </configuration> </plugin>
Surefire parameters: http://maven.apache.org/plugins/maven-surefire-plugin/test-mojo.html
Edit (January 2014):
As Peter Perhác pointed out, the forkMode parameter is deprecated since Surefire 2.14. Beginning from Surefire 2.14 use this instead:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.16</version>
<configuration>
<reuseForks>false</reuseForks>
<forkCount>1</forkCount>
</configuration>
</plugin>
For more information see Fork Options and Parallel Test Execution
You can try using the standard W3C way:
.transition { transition: all 0.2s, top 0s, left 0s, width 0s, height 0s; }
Here is some information about one more source of the JSESSIONID
cookie:
I was just debugging some Java code that runs on a tomcat server. I was not calling request.getSession()
explicitly anywhere in my code but I noticed that a JSESSIONID
cookie was still being set.
I finally took a look at the generated Java code corresponding to a JSP in the work directory under Tomcat.
It appears that, whether you like it or not, if you invoke a JSP from a servlet, JSESSIONID
will get created!
Added: I just found that by adding the following JSP directive:
<%@ page session="false" %>
you can disable the setting of JSESSIONID
by a JSP.
it worked. Just modified it
global $woocommerce, $post;
$order = new WC_Order($post->ID);
//to escape # from order id
$order_id = trim(str_replace('#', '', $order->get_order_number()));
I also faced the same problem recently and sourcing nvm bash script by using source ~/.nvm/nvm.sh resolved this issue.
And, of course
("ABCD"[2] == 2["ABCD"]) && (2["ABCD"] == 'C') && ("ABCD"[2] == 'C')
The main reason for this was that back in the 70's when C was designed, computers didn't have much memory (64KB was a lot), so the C compiler didn't do much syntax checking. Hence "X[Y]
" was rather blindly translated into "*(X+Y)
"
This also explains the "+=
" and "++
" syntaxes. Everything in the form "A = B + C
" had the same compiled form. But, if B was the same object as A, then an assembly level optimization was available. But the compiler wasn't bright enough to recognize it, so the developer had to (A += C
). Similarly, if C
was 1
, a different assembly level optimization was available, and again the developer had to make it explicit, because the compiler didn't recognize it. (More recently compilers do, so those syntaxes are largely unnecessary these days)
To remove the diacritics, use iconv:
$val = iconv('ISO-8859-1','ASCII//TRANSLIT',$val);
or
$val = iconv('UTF-8','ASCII//TRANSLIT',$val);
note that php has some weird bug in that it (sometimes?) needs to have a locale set to make these conversions work, using setlocale().
edit tested, it gets all of your diacritics out of the box:
$val = "á|â|à|å|ä ð|é|ê|è|ë í|î|ì|ï ó|ô|ò|ø|õ|ö ú|û|ù|ü æ ç ß abc ABC 123";
echo iconv('UTF-8','ASCII//TRANSLIT',$val);
output (updated 2019-12-30)
a|a|a|a|a d|e|e|e|e i|i|i|i o|o|o|o|o|o u|u|u|u ae c ss abc ABC 123
Note that ð
is correctly transliterated to d
instead of o
, as in the accepted answer.
This error is mainly due to processor architecture incompatibility with Framework installed ei x86 vs x64 The solution: Go to solution explorer>project properties>Compile tab>Advanced Compile Options There you have to change Target CPU from X64 to X86 Save new setting and recompile your solution. I tried it and it worked very fine. Hope this will help you out. Malek
If the Proxy is which you trust, you can try: (Assume the Proxy IP is 151.101.2.10
)
<?php
$trustProxyIPs = ['151.101.2.10'];
$clientIP = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : NULL;
if (in_array($clientIP, $trustProxyIPs)) {
$headers = ['HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR'];
foreach ($headers as $key => $header) {
if (isset($_SERVER[$header]) && filter_var($_SERVER[$header], FILTER_VALIDATE_IP)) {
$clientIP = $_SERVER[$header];
break;
}
}
}
echo $clientIP;
This will prevent forged forward header by direct requested clients, and get real IP via trusted Proxies.
You could use traits, which, hopefully, will be available from PHP 5.4.
Traits is a mechanism for code reuse in single inheritance languages such as PHP. A Trait is intended to reduce some limitations of single inheritance by enabling a developer to reuse sets of methods freely in several independent classes living in different class hierarchies. The semantics of the combination of Traits and classes is defined in a way, which reduces complexity and avoids the typical problems associated with multiple inheritance and Mixins.
They are recognized for their potential in supporting better composition and reuse, hence their integration in newer versions of languages such as Perl 6, Squeak, Scala, Slate and Fortress. Traits have also been ported to Java and C#.
More information: https://wiki.php.net/rfc/traits
There are two possibilities.
You forgot to put the %id%
in the jstack
call.
jstack %id% > jstack.txt
So the whole correct batch file should be:
@echo off
set /p id=Enter ID:
echo %id%
jstack %id% > jstack.txt
And/Or 2. You did put it in the code (and forgot to tell us in the question) but when you ran the batch file you hit the Enter key instead of typing an ID (say 1234).
What's happening is the result of these two mistakes:
jstack
is supposed to be called with the id that you supply it.
But in your case (according to the code you supplied in the question) you called it without any variable. You wrote:
jstack > jstack.txt
So when you run jstack
with no variable it outputs the following:
Terminate batch file Y/N?
Your second mistake is that you pressed Enter instead of giving a value when the program asked you: Enter ID:
. If you would have put in an ID at this point, say 1234, the %id%
variable would become that value, in our case 1234. But you did NOT supply a value and instead pressed Enter. When you don't give the variable any value, and if that variable was not set to anything else before, then the variable %id%
is set to the prompt of the set
command!! So now %id%
is set to Enter ID:
which was echoed on your screen as requested in the batch file BEFORE you called the jstack.
But I suspect you DID have the jstack %id% > jstack.txt
in your batch file code with the %id
(and omitted it by mistake from the question), and that you hit enter without typing in an id. The batch program then echoed the id, which is now "Enter ID:", and then ran jstack Enter ID: > jstack.txt
Jstack itself echoed the input, encountered a mistake and asked to terminate.
And all this was written into the jstack.txt file.
The pyplot functions you are calling, axhline()
and axvline()
draw lines that span a portion of the axis range, regardless of coordinates. The parameters xmin
or ymin
use value 0.0 as the minimum of the axis and 1.0 as the maximum of the axis.
Instead, use plt.plot((x1, x2), (y1, y2), 'k-')
to draw a line from the point (x1, y1) to the point (x2, y2) in color k. See pyplot.plot
.
in my case it's a maven project
delete the project from eclipse leaving the sources close eclipse delete from filesystem
.target/ .classpath .project .settings/ open eclipse Again Import Maven Projects
This solved the problem
If you've got git-bash
installed (which comes with Git, Github for Windows, or Visual Studio 2015), then that includes a Windows version of ssh-keygen
.
https://help.github.com/articles/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent/
This approach will not limit element's width when using margins in flexbox
top: 0; left: 0;
transform: translate(calc(50vw - 50%));
Also for centering it vertically
top: 0; left: 0;
transform: translate(calc(50vw - 50%), calc(50vh - 50%));
First figure out which upstream is slowing by consulting the nginx error log file and adjust the read time out accordingly in my case it was fastCGI
2017/09/27 13:34:03 [error] 16559#16559: *14381 upstream timed out (110: Connection timed out) while reading response header from upstream, client:xxxxxxxxxxxxxxxxxxxxxxxxx", upstream: "fastcgi://unix:/var/run/php/php5.6-fpm.sock", host: "xxxxxxxxxxxxxxx", referrer: "xxxxxxxxxxxxxxxxxxxx"
So i have to adjust the fastcgi_read_timeout in my server configuration
location ~ \.php$ {
fastcgi_read_timeout 240;
...
}
See: original post
Eclipse doesn't consult the
JAVA_HOME
variable
You should specify where Eclipse should find your JDK in the file eclipse.ini
. Specifically, the following parameter (note that it is 2 separate lines in the ini file):
-vm
C:\Java\JDK\1.8\bin\javaw.exe
or wherever your javaw.exe happens to be.
Note: The format of the ini
file is very particular; make sure to consult https://wiki.eclipse.org/Eclipse.ini to ensure you get it exactly right.
Loop in reverse by decrementing i
to avoid the problem:
for (var i = arrayOfObjects.length - 1; i >= 0; i--) {
var obj = arrayOfObjects[i];
if (listToDelete.indexOf(obj.id) !== -1) {
arrayOfObjects.splice(i, 1);
}
}
Or use filter
:
var newArray = arrayOfObjects.filter(function(obj) {
return listToDelete.indexOf(obj.id) === -1;
});
Try this demo please: http://jsfiddle.net/sgpw2/
Thanks Jan for spaces \s
rest there is some good detail in this link:
http://www.jquery4u.com/syntax/jquery-basic-regex-selector-examples/#.UHKS5UIihlI
Hope it fits your need :)
code
$(function() {
$("#field").bind("keyup", function(event) {
var regex = /^[a-zA-Z\s]+$/;
if (regex.test($("#field").val())) {
$('.validation').html('valid');
} else {
$('.validation').html("FAIL regex");
}
});
});?
The only thing I can add to Stephan202's answer is a recommendation that you take a look at David Beazley's PyCon '08 presentation "Generator Tricks for Systems Programmers," which is the best single explanation of the how and why of generators that I've seen anywhere. This is the thing that took me from "Python looks kind of fun" to "This is what I've been looking for." It's at http://www.dabeaz.com/generators/.
For inserting at a particular position k
, you need to traverse the list till the position k-1
and then do the insert.
[You need not create a new node to traverse to that position as you did in your code] You should traverse from the head node.
You can use the filter
function to apply more complicated regex matching.
Here's an example which would just match the first three divs:
$('div')_x000D_
.filter(function() {_x000D_
return this.id.match(/abc+d/);_x000D_
})_x000D_
.html("Matched!");
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<div id="abcd">Not matched</div>_x000D_
<div id="abccd">Not matched</div>_x000D_
<div id="abcccd">Not matched</div>_x000D_
<div id="abd">Not matched</div>
_x000D_
pls refer this https://stackoverflow.com/a/1972404/951045
TelephonyManager mngr = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
mngr.getDeviceId();
add READ_PHONE_STATE
permission to AndroidManifest.xml
Just to add a bit of extra info over the right solution. Be aware that you'll need this class org.apache.catalina.filters.CorsFilter. So in order to have it, if your tomcat is not 7.0.41 or higher, download 'tomcat-catalina.7.0.41.jar' or higher ( you can do it from http://mvnrepository.com/artifact/org.apache.tomcat/tomcat-catalina ) and put it in the 'lib' folder inside Tomcat installation folders. I actually used 7.0.42 Hope it helps!
In both Python 2 and 3, using the module pathlib2:
import posixpath # to generate unix paths
from pathlib2 import PurePath, PureWindowsPath, PurePosixPath
def path2unix(path, nojoin=True, fromwinpath=False):
"""From a path given in any format, converts to posix path format
fromwinpath=True forces the input path to be recognized as a Windows path (useful on Unix machines to unit test Windows paths)"""
if not path:
return path
if fromwinpath:
pathparts = list(PureWindowsPath(path).parts)
else:
pathparts = list(PurePath(path).parts)
if nojoin:
return pathparts
else:
return posixpath.join(*pathparts)
Usage:
In [9]: path2unix('lala/lolo/haha.dat')
Out[9]: ['lala', 'lolo', 'haha.dat']
In [10]: path2unix(r'C:\lala/lolo/haha.dat')
Out[10]: ['C:\\', 'lala', 'lolo', 'haha.dat']
In [11]: path2unix(r'C:\lala/lolo/haha.dat') # works even with malformatted cases mixing both Windows and Linux path separators
Out[11]: ['C:\\', 'lala', 'lolo', 'haha.dat']
With your testcase:
In [12]: testcase = paths = ['a/b/c/', 'a/b/c', '\\a\\b\\c', '\\a\\b\\c\\', 'a\\b\\c',
...: ... 'a/b/../../a/b/c/', 'a/b/../../a/b/c']
In [14]: for t in testcase:
...: print(path2unix(t)[-1])
...:
...:
c
c
c
c
c
c
c
The idea here is to convert all paths into the unified internal representation of pathlib2
, with different decoders depending on the platform. Fortunately, pathlib2
includes a generic decoder called PurePath
that should work on any path. In case this does not work, you can force the recognition of windows path using fromwinpath=True
. This will split the input string into parts, the last one is the leaf you are looking for, hence the path2unix(t)[-1]
.
If the argument nojoin=False
, the path will be joined back, so that the output is simply the input string converted to a Unix format, which can be useful to compare subpaths across platforms.
A small usage of np.nan ! = np.nan
s[s==s]
Out[953]:
0 1.0
1 2.0
2 3.0
3 4.0
5 5.0
dtype: float64
More Info
np.nan == np.nan
Out[954]: False
ng serve
This command run in your terminal after your in project folder location like ~/my-app$
Then run the command - it will show the URl NG Live Development Server is listening on localhost:4200
Open your browser on http://localhost:4200
I had the same issue when I clone my project from Git and directly build the solution first time. Instead of that go to the local repository in file explorer and double click the solution file (.sln) solved my issue.
$diffPricePercent = (($actual * 100) / $itemCost) / $itemQty;
$itemCost
and $itemQty
are returning null
or zero, check them what they come with to code from user input
also to check if it's not empty data add:
if (!empty($_POST['num1'])) {
$itemQty = $_POST['num1'];
}
and you can check this link for POST validation before using it in variable
https://www.virendrachandak.com/techtalk/php-isset-vs-empty-vs-is_null/
I was working with spring boot jpa and fixed by implementing @EnableTransactionManagement
Have you googled about it - insert update delete access vb.net, there are lots of reference about this.
Insert Update Delete Navigation & Searching In Access Database Using VB.NET
what could be the easier way to connect and manipulate the DB?
Use OleDBConnection class to make connection with DB
is it by using MS ACCESS 2003 or MS ACCESS 2007?
you can use any you want to use or your client will use on their machine.
it seems that you want to find some example of opereations fo the database. Here is an example of Access 2010 for your reference:
Example code snippet:
Imports System
Imports System.Data
Imports System.Data.OleDb
Public Class DBUtil
Private connectionString As String
Public Sub New()
Dim con As New OleDb.OleDbConnection
Dim dbProvider As String = "Provider=Microsoft.ace.oledb.12.0;"
Dim dbSource = "Data Source=d:\DB\Database11.accdb"
connectionString = dbProvider & dbSource
End Sub
Public Function GetCategories() As DataSet
Dim query As String = "SELECT * FROM Categories"
Dim cmd As New OleDbCommand(query)
Return FillDataSet(cmd, "Categories")
End Function
Public SubUpdateCategories(ByVal name As String)
Dim query As String = "update Categories set name = 'new2' where name = ?"
Dim cmd As New OleDbCommand(query)
cmd.Parameters.AddWithValue("Name", name)
Return FillDataSet(cmd, "Categories")
End Sub
Public Function GetItems() As DataSet
Dim query As String = "SELECT * FROM Items"
Dim cmd As New OleDbCommand(query)
Return FillDataSet(cmd, "Items")
End Function
Public Function GetItems(ByVal categoryID As Integer) As DataSet
'Create the command.
Dim query As String = "SELECT * FROM Items WHERE Category_ID=?"
Dim cmd As New OleDbCommand(query)
cmd.Parameters.AddWithValue("category_ID", categoryID)
'Fill the dataset.
Return FillDataSet(cmd, "Items")
End Function
Public Sub AddCategory(ByVal name As String)
Dim con As New OleDbConnection(connectionString)
'Create the command.
Dim insertSQL As String = "INSERT INTO Categories "
insertSQL &= "VALUES(?)"
Dim cmd As New OleDbCommand(insertSQL, con)
cmd.Parameters.AddWithValue("Name", name)
Try
con.Open()
cmd.ExecuteNonQuery()
Finally
con.Close()
End Try
End Sub
Public Sub AddItem(ByVal title As String, ByVal description As String, _
ByVal price As Decimal, ByVal categoryID As Integer)
Dim con As New OleDbConnection(connectionString)
'Create the command.
Dim insertSQL As String = "INSERT INTO Items "
insertSQL &= "(Title, Description, Price, Category_ID)"
insertSQL &= "VALUES (?, ?, ?, ?)"
Dim cmd As New OleDb.OleDbCommand(insertSQL, con)
cmd.Parameters.AddWithValue("Title", title)
cmd.Parameters.AddWithValue("Description", description)
cmd.Parameters.AddWithValue("Price", price)
cmd.Parameters.AddWithValue("CategoryID", categoryID)
Try
con.Open()
cmd.ExecuteNonQuery()
Finally
con.Close()
End Try
End Sub
Private Function FillDataSet(ByVal cmd As OleDbCommand, ByVal tableName As String) As DataSet
Dim con As New OleDb.OleDbConnection
Dim dbProvider As String = "Provider=Microsoft.ace.oledb.12.0;"
Dim dbSource = "Data Source=D:\DB\Database11.accdb"
connectionString = dbProvider & dbSource
con.ConnectionString = connectionString
cmd.Connection = con
Dim adapter As New OleDbDataAdapter(cmd)
Dim ds As New DataSet()
Try
con.Open()
adapter.Fill(ds, tableName)
Finally
con.Close()
End Try
Return ds
End Function
End Class
Refer these links:
Insert, Update, Delete & Search Values in MS Access 2003 with VB.NET 2005
INSERT, DELETE, UPDATE AND SELECT Data in MS-Access with VB 2008
How Add new record ,Update record,Delete Records using Vb.net Forms when Access as a back
I know this is old, but I just wanted to point out for NETMF (.Net MicroFramework), you can easily do this:
string response = Resources.GetString(Resources.StringResources.MyFileName);
Since NETMF doesn't have GetManifestResourceStream
Make sure you somehow use results which are computed in benchmarked code. Otherwise your code can be optimized away.
Check out Datejs. Their built in formatters can do this: http://code.google.com/p/datejs/wiki/APIDocumentation#toString
It's a really handy library, especially if you are planning on doing other things with date objects.
Although there are many ways to do this. But if you want to do it in an easy way and want to format text before writing it to log file. You can create a helper function for this.
if (!function_exists('logIt')) {
function logIt($logMe)
{
$logFilePath = storage_path('logs/cron.log.'.date('Y-m-d').'.log');
$cronLogFile = fopen($logFilePath, "a");
fwrite($cronLogFile, date('Y-m-d H:i:s'). ' : ' .$logMe. PHP_EOL);
fclose($cronLogFile);
}
}
I also encountered such an issue while trying to set up a project using Docker-Compose on Ubuntu.
The Docker had no access to internet at all, when I tried to ping any IP address or nslookup some URL - it failed all the time.
I tried all the possible solutions with DNS resolution described above to no avail.
I spent the whole day trying to find out what the heck is going on, and finally found out that the cause of all the trouble was the antivirus, in particular it's firewall which for some reason blocked Docker from getting the IP address and port.
When I disabled it - everything worked fine.
So, if you have an antivirus installed and nothing helps fix the issue - the problem could be the firewall of the antivirus.
Are you sure you selected Console Application? I'm running VS 2010 and with the vanilla settings a C# console app builds to \bin\debug. Try to create a new Console Application project, with the language set to C#. Build the project, and go to Project/[Console Application 1]Properties. In the Build tab, what is the Output path? It should default to bin\debug, unless you have some restricted settings on your workstation,etc. Also review the build output window and see if any errors are being thrown - in which case nothing will be built to the output folder, of course...
keydown
with event.key === "Backspace" or "Delete"
More recent and much cleaner: use event.key
. No more arbitrary number codes!
input.addEventListener('keydown', function(event) {
const key = event.key; // const {key} = event; ES6+
if (key === "Backspace" || key === "Delete") {
return false;
}
});
Modern style:
input.addEventListener('keydown', ({key}) => {
if (["Backspace", "Delete"].includes(key)) {
return false
}
})
If you're using PHP 5.5 or PHP 7 above, you may want to use:
function isTodayWeekend() {
return in_array(date("l"), ["Saturday", "Sunday"]);
}
and it will return "true" if today is weekend and "false" if not.
With the verify
parameter you can provide a custom certificate authority bundle
requests.get(url, verify=path_to_bundle_file)
From the docs:
You can pass
verify
the path to a CA_BUNDLE file with certificates of trusted CAs. This list of trusted CAs can also be specified through the REQUESTS_CA_BUNDLE environment variable.
Try:
select distinct T1.id
from TABLE1 T1
where not exists (select distinct T2.id
from TABLE2 T2
where T2.id = T1.id)
With sql oracle 11g+
The real answer is to use:
Color.parseColor(myPassedColor)
in Android, myPassedColor
being the hex
value like #000
or #000000
or #00000000
.
However, this function does not support shorthand hex values such as #000
.
Apart from read the big file line by line, you also can read it chunk by chunk. For more refer to this article
var offset = 0;
var chunkSize = 2048;
var chunkBuffer = new Buffer(chunkSize);
var fp = fs.openSync('filepath', 'r');
var bytesRead = 0;
while(bytesRead = fs.readSync(fp, chunkBuffer, 0, chunkSize, offset)) {
offset += bytesRead;
var str = chunkBuffer.slice(0, bytesRead).toString();
var arr = str.split('\n');
if(bytesRead = chunkSize) {
// the last item of the arr may be not a full line, leave it to the next chunk
offset -= arr.pop().length;
}
lines.push(arr);
}
console.log(lines);
I know it's a very old question, but is the first in my google search and after some time I got how to solve this.
find node on your windows with
$ npm install -g which
$ which node
after cd
into the directory, inside the directory cd
into node_modules\npm folder and finally:
$ npm install node-gyp@latest
here worked, the answer is from this site
public static String removechar(String fromString, Character character) {
int indexOf = fromString.indexOf(character);
if(indexOf==-1)
return fromString;
String front = fromString.substring(0, indexOf);
String back = fromString.substring(indexOf+1, fromString.length());
return front+back;
}
For those who is not able to access/install at
in environment, can use custom script:
#!/bin/bash
if [ $# -lt 2 ]; then
echo ""
echo "Syntax Error!"
echo "Usage: $0 <shell script> <datetime>"
echo "<datetime> format: %Y%m%d%H%M"
echo "Example: $0 /home/user/scripts/server_backup.sh 202008142350"
echo ""
exit 1
fi
while true; do
t=$(date +%Y%m%d%H%M);
if [ $t -eq $2 ]; then
/bin/bash $1
echo DONE $(date);
break;
fi;
sleep 1;
done
Let's name the script as run1time.sh Example could be something like:
nohup bash run1time.sh /path/to/your/script.sh 202008150300 &
Another option that has not been mentioned is just creating the unit test class as a child of the object that you are testing. NUnit Example:
[TestFixture]
public class UnitTests : ObjectWithPrivateMethods
{
[Test]
public void TestSomeProtectedMethod()
{
Assert.IsTrue(this.SomeProtectedMethod() == true, "Failed test, result false");
}
}
This would allow easy testing of private and protected (but not inherited private) methods, and it would allow you to keep all your tests separate from the real code so you aren't deploying test assemblies to production. Switching your private methods to protected methods would be acceptable in a lot of inherited objects, and it is a pretty simple change to make.
HOWEVER...
While this is an interesting approach to solving the problem of how to test hidden methods, I am unsure that I would advocate that this is the correct solution to the problem in all cases. It seems a little odd to be internally testing an object, and I suspect there might be some scenarios that this approach will blow up on you. (Immutable objects for example, might make some tests really hard).
While I mention this approach, I would suggest that this is more of a brainstormed suggestion than a legitimate solution. Take it with a grain of salt.
EDIT: I find it truly hilarious that people are voting this answer down, since I explicitly describe this as a bad idea. Does that mean that people are agreeing with me? I am so confused.....
/* create new name file */
$filename = uniqid() . "-" . time(); // 5dab1961e93a7-1571494241
$extension = pathinfo( $_FILES["file"]["name"], PATHINFO_EXTENSION ); // jpg
$basename = $filename . "." . $extension; // 5dab1961e93a7_1571494241.jpg
$source = $_FILES["file"]["tmp_name"];
$destination = "../img/imageDirectory/{$basename}";
/* move the file */
move_uploaded_file( $source, $destination );
echo "Stored in: {$destination}";
$('a').click(function(){
$('embed').remove();
$('body').append('<embed src="/path/to/your/sound.wav" autostart="true" hidden="true" loop="false">');
});
Try:
num3 = 100000000000LL;
And BTW, in C++ this is a compiler extension, the standard does not define long long, thats part of C99.
Gnome terminal defaults to ControlShiftv
OSX terminal defaults to Commandv. You can also use CommandControlv to paste the text in escaped form.
Windows 7 terminal defaults to CtrlShiftInsert
Run the following query from Management Studio on a running process:
DBCC inputbuffer( spid# )
This will return the SQL currently being run against the database for the SPID provided. Note that you need appropriate permissions to run this command.
This is better than running a trace since it targets a specific SPID. You can see if it's long running based on its CPUTime and DiskIO.
Example to get details of SPID 64:
DBCC inputbuffer(64)
After updating my Android SDK I stumbled upon this very problem and I tried many ways without success. What was most irritating to me when searching for a fix, were the lots of answers suggesting to change the CompileSdkVersion to a certain number while obviously this number changes with time, so here's what I did instead.
I created a new project and ran it on the emulator to make sure it's working, then checked its "\android\app\build.gradle" file and copied the numeric value of CompileSdkVersion and pasted into the same file in my other project that could not be built properly anymore. Now my problem's gone. Hope that helps.
If found this alteration to Krzysztof answer helped my issue
$('#' + parentId + ' .collapse').on('show.bs.collapse', function (e) {
var all = $('#' + parentId).find('.collapse');
var actives = $('#' + parentId).find('.in, .collapsing');
all.each(function (index, element) {
$(element).collapse('hide');
})
actives.each(function (index, element) {
$(element).collapse('show');
})
})
if you have nested panels then you may also need to specify which ones by adding another class name to distinguish between them and add this to the a selector in the above JavaScript
Another, very simple way of monitoring tables is table versioning. The system is proven working in constructions such as DNS synchronization. To make it work you create a table containing table names and table versions as decimal
or bigint.
In each table that you need monitored, create trigger on insert, update and delete that will increment appropriate table version in versioning table when executed. If you expect any of the monitored tables to be altered often, you need to provision for version reusing. Finally, in your application, every time you query monitored table, you also query its version and store it. When you go to alter the monitored table from your app, you first query its current version and process the change only if the version is unchanged. You can have stored proc on sql server do that work for you.
This is extremely simple but proven solid solution. It has specific functional use (to ensure data consistency) and is light on resources (you do not raise brokered events that you would not watch for) but needs application to actively check for changes rather than passively wait for event to happen.
Normally a jdk installation has javac in the environment path variables ... so if you check for javac in the path, that's pretty much a good indicator that you have a jdk installed.
Here is an example for Python 3 that you can edit for Python 2 ;)
from tkinter import *
from PIL import ImageTk, Image
from tkinter import filedialog
import os
root = Tk()
root.geometry("550x300+300+150")
root.resizable(width=True, height=True)
def openfn():
filename = filedialog.askopenfilename(title='open')
return filename
def open_img():
x = openfn()
img = Image.open(x)
img = img.resize((250, 250), Image.ANTIALIAS)
img = ImageTk.PhotoImage(img)
panel = Label(root, image=img)
panel.image = img
panel.pack()
btn = Button(root, text='open image', command=open_img).pack()
root.mainloop()
I had two problems with the accepted answer.
Screen
class are incorrect when display scaling is used and your application is not declared dpiAware.Here's my updated solution using the Screen.AllScreens
static property and calling EnumDisplaySettings
using p/invoke to get the real screen resolution.
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Windows.Forms;
class Program
{
const int ENUM_CURRENT_SETTINGS = -1;
static void Main()
{
foreach (Screen screen in Screen.AllScreens)
{
DEVMODE dm = new DEVMODE();
dm.dmSize = (short)Marshal.SizeOf(typeof(DEVMODE));
EnumDisplaySettings(screen.DeviceName, ENUM_CURRENT_SETTINGS, ref dm);
using (Bitmap bmp = new Bitmap(dm.dmPelsWidth, dm.dmPelsHeight))
using (Graphics g = Graphics.FromImage(bmp))
{
g.CopyFromScreen(dm.dmPositionX, dm.dmPositionY, 0, 0, bmp.Size);
bmp.Save(screen.DeviceName.Split('\\').Last() + ".png");
}
}
}
[DllImport("user32.dll")]
public static extern bool EnumDisplaySettings(string lpszDeviceName, int iModeNum, ref DEVMODE lpDevMode);
[StructLayout(LayoutKind.Sequential)]
public struct DEVMODE
{
private const int CCHDEVICENAME = 0x20;
private const int CCHFORMNAME = 0x20;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 0x20)]
public string dmDeviceName;
public short dmSpecVersion;
public short dmDriverVersion;
public short dmSize;
public short dmDriverExtra;
public int dmFields;
public int dmPositionX;
public int dmPositionY;
public ScreenOrientation dmDisplayOrientation;
public int dmDisplayFixedOutput;
public short dmColor;
public short dmDuplex;
public short dmYResolution;
public short dmTTOption;
public short dmCollate;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 0x20)]
public string dmFormName;
public short dmLogPixels;
public int dmBitsPerPel;
public int dmPelsWidth;
public int dmPelsHeight;
public int dmDisplayFlags;
public int dmDisplayFrequency;
public int dmICMMethod;
public int dmICMIntent;
public int dmMediaType;
public int dmDitherType;
public int dmReserved1;
public int dmReserved2;
public int dmPanningWidth;
public int dmPanningHeight;
}
}
References:
https://stackoverflow.com/a/36864741/987968 http://pinvoke.net/default.aspx/user32/EnumDisplaySettings.html?diff=y
For .NET 4.0 and higher, you can compare elements in array or tuples using the StructuralComparisons type:
object[] a1 = { "string", 123, true };
object[] a2 = { "string", 123, true };
Console.WriteLine (a1 == a2); // False (because arrays is reference types)
Console.WriteLine (a1.Equals (a2)); // False (because arrays is reference types)
IStructuralEquatable se1 = a1;
//Next returns True
Console.WriteLine (se1.Equals (a2, StructuralComparisons.StructuralEqualityComparer));
Code example of ItemListener
implementation
class ItemChangeListener implements ItemListener{
@Override
public void itemStateChanged(ItemEvent event) {
if (event.getStateChange() == ItemEvent.SELECTED) {
Object item = event.getItem();
// do something with object
}
}
}
Now we will get only selected item.
Then just add listener to your JComboBox
addItemListener(new ItemChangeListener());
I think that this is the correct way:
class Game extends Eloquent {
// many more stuff here
// relation without any constraints ...works fine
public function videos() {
return $this->hasMany('Video');
}
// results in a "problem", se examples below
public function available_videos() {
return $this->videos()->where('available','=', 1);
}
}
And then you'll have to
$game = Game::find(1);
var_dump( $game->available_videos()->get() );
In case of Windows, if you can't find setenv.bat, in the 2nd line of catalina.bat (after @echo off) add this:
SET APP_MASTER_PASSWORD=foo
May not be the best approach, but works
Now, with EF Core you can convert data type transparently in your AppDbContext
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// i.e. Store TimeSpan as string (custom)
modelBuilder
.Entity<YourClass>()
.Property(x => x.YourTimeSpan)
.HasConversion(
timeSpan => timeSpan.ToString(), // To DB
timeSpanString => TimeSpan.Parse(timeSpanString) // From DB
);
// i.e. Store TimeSpan as string (using TimeSpanToStringConverter)
modelBuilder
.Entity<YourClass>()
.Property(x => x.YourTimeSpan)
.HasConversion(new TimeSpanToStringConverter());
// i.e. Store TimeSpan as number of ticks (custom)
modelBuilder
.Entity<YourClass>()
.Property(x => x.YourTimeSpan)
.HasConversion(
timeSpan => timeSpan.Ticks, // To DB
timeSpanString => TimeSpan.FromTicks(timeSpanString) // From DB
);
// i.e. Store TimeSpan as number of ticks (using TimeSpanToTicksConverter)
modelBuilder
.Entity<YourClass>()
.Property(x => x.YourTimeSpan)
.HasConversion(new TimeSpanToTicksConverter());
}
Check for null in your check() method and return an invalid value such as -1 or zero if null. Then the check would be for that value rather than passing the null along. This would be a normal thing to do in old time 'C'.
When a chip gets power all of it's registers contain random values. It's not possible to have an an initial value. It will always be random.
This is why we have reset signals, to reset registers to a known value. The reset is controlled by something off chip, and we write our code to use it.
always @(posedge clk) begin
if (reset == 1) begin // For an active high reset
data_reg = 8'b10101011;
end else begin
data_reg = next_data_reg;
end
end
You can return generic wildcard <?>
to return Success
and Error
on a same request mapping method
public ResponseEntity<?> method() {
boolean b = // some logic
if (b)
return new ResponseEntity<Success>(HttpStatus.OK);
else
return new ResponseEntity<Error>(HttpStatus.CONFLICT); //appropriate error code
}
@Mark Norman answer is the correct approach
I can see it's an old question, if you want to put other HTML inside could use the radiobutton with GroupName propery same in all radiobuttons and in the Text property set something like an image or the html you need.
<asp:RadioButton GroupName="group1" runat="server" ID="paypalrb" Text="<img src='https://www.paypalobjects.com/webstatic/mktg/logo/bdg_secured_by_pp_2line.png' border='0' alt='Secured by PayPal' style='width: 103px; height: 61px; padding:10px;'>" />
The besty practice is to use '/' and a so called 'raw string' to define file path in Python.
path = r"C:/Test.py"
However, a normal program may not have the permission to write in the C:
drive root directory. You may need to allow your program to do so, or choose something more reasonable since you probably not need to do so.
Felt the need to add this better answer, as nothing except BackgroundWorker
seemed to help me, and the answer dealing with that thus far was woefully incomplete. This is how you would update a XAML page called MainWindow
that has an Image tag like this:
<Image Name="imgNtwkInd" Source="Images/network_on.jpg" Width="50" />
with a BackgroundWorker
process to show if you are connected to the network or not:
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
public partial class MainWindow : Window
{
private BackgroundWorker bw = new BackgroundWorker();
public MainWindow()
{
InitializeComponent();
// Set up background worker to allow progress reporting and cancellation
bw.WorkerReportsProgress = true;
bw.WorkerSupportsCancellation = true;
// This is your main work process that records progress
bw.DoWork += new DoWorkEventHandler(SomeClass.DoWork);
// This will update your page based on that progress
bw.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged);
// This starts your background worker and "DoWork()"
bw.RunWorkerAsync();
// When this page closes, this will run and cancel your background worker
this.Closing += new CancelEventHandler(Page_Unload);
}
private void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
BitmapImage bImg = new BitmapImage();
bool connected = false;
string response = e.ProgressPercentage.ToString(); // will either be 1 or 0 for true/false -- this is the result recorded in DoWork()
if (response == "1")
connected = true;
// Do something with the result we got
if (!connected)
{
bImg.BeginInit();
bImg.UriSource = new Uri("Images/network_off.jpg", UriKind.Relative);
bImg.EndInit();
imgNtwkInd.Source = bImg;
}
else
{
bImg.BeginInit();
bImg.UriSource = new Uri("Images/network_on.jpg", UriKind.Relative);
bImg.EndInit();
imgNtwkInd.Source = bImg;
}
}
private void Page_Unload(object sender, CancelEventArgs e)
{
bw.CancelAsync(); // stops the background worker when unloading the page
}
}
public class SomeClass
{
public static bool connected = false;
public void DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker bw = sender as BackgroundWorker;
int i = 0;
do
{
connected = CheckConn(); // do some task and get the result
if (bw.CancellationPending == true)
{
e.Cancel = true;
break;
}
else
{
Thread.Sleep(1000);
// Record your result here
if (connected)
bw.ReportProgress(1);
else
bw.ReportProgress(0);
}
}
while (i == 0);
}
private static bool CheckConn()
{
bool conn = false;
Ping png = new Ping();
string host = "SomeComputerNameHere";
try
{
PingReply pngReply = png.Send(host);
if (pngReply.Status == IPStatus.Success)
conn = true;
}
catch (PingException ex)
{
// write exception to log
}
return conn;
}
}
For more information: https://msdn.microsoft.com/en-us/library/cc221403(v=VS.95).aspx
Code for background image of a Button in Swift 3.0
buttonName.setBackgroundImage(UIImage(named: "facebook.png"), for: .normal)
Hope this will help someone.
i came across a similar situation using booleans where I wanted to avoid calling b() if a was already false.
This worked for me:
a &= a && b()
The bin/XXX.apk
file can be built automatically as soon as you save any source file:
Window/Preferences, Android/Build, uncheck "skip packaging and indexing..."
I've been using jquery-json for 6 months and it works great. It's very simple to use:
var myObj = {foo: "bar", "baz": "wockaflockafliz"};
$.toJSON(myObj);
// Result: {"foo":"bar","baz":"wockaflockafliz"}
CVertex, make sure to review your code, and, if that doesn't reveal anything, post it. I was just enabling this on a test ASP.NET site I was working on, and it works.
Actually, at some point I had an issue on my code. I didn't spot it until I had a simpler version on a console program and saw it was working (no change on the Gmail side as you were worried about). The below code works just like the samples you referred to:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Mail;
using System.Net;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
var client = new SmtpClient("smtp.gmail.com", 587)
{
Credentials = new NetworkCredential("[email protected]", "mypwd"),
EnableSsl = true
};
client.Send("[email protected]", "[email protected]", "test", "testbody");
Console.WriteLine("Sent");
Console.ReadLine();
}
}
}
I also got it working using a combination of web.config, http://msdn.microsoft.com/en-us/library/w355a94k.aspx and code (because there is no matching EnableSsl
in the configuration file :( ).
Code coverage basically tells you how much of your code is covered under tests. For example, if you have 90% code coverage, it means 10% of the code is not covered under tests.
I know you might be thinking that if 90% of the code is covered, it's good enough, but you have to look from a different angle. What is stopping you from getting 100% code coverage?
A good example will be this:
if(customer.IsOldCustomer())
{
}
else
{
}
Now, in the code above, there are two paths/branches. If you are always hitting the "YES" branch, you are not covering the "else" part and it will be shown in the Code Coverage results. This is good because now you know that what is not covered and you can write a test to cover the "else" part. If there was no code coverage, you are just sitting on a time bomb, waiting to explode.
NCover is a good tool to measure code coverage.
i.e. projects beginning with <Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
Add the following to your csproj on your "main"/root project
<PropertyGroup>
<ContentSQLiteInteropFiles>true</ContentSQLiteInteropFiles>
<CopySQLiteInteropFiles>false</CopySQLiteInteropFiles>
<CleanSQLiteInteropFiles>false</CleanSQLiteInteropFiles>
<CollectSQLiteInteropFiles>false</CollectSQLiteInteropFiles>
</PropertyGroup>
i.e. projects beginning with <Project Sdk="Microsoft.NET.Sdk.*">
Add PrivateAssets="none"
to each ProjectReference/PackageImport in the dependency chain down to the System.Data.Sqlite PackageImport
ex:
<PackageReference Include="System.Data.SQLite.Core" Version="1.0.110" PrivateAssets="none"/>
df[df$aged <= df$laclen, ]
Should do the trick. The square brackets allow you to index based on a logical expression.
you can just do this:
string id = GridName.DataKeys[Convert.ToInt32(e.CommandArgument)].Value.ToString();
The bytes int can hold depends on what you compiled it for, so when you compile your program for 32 bit processors, it holds numbers from 2^32/2 to -2^32/2+1, while compiled for 64 bit it can hold from 2^64/2 to -2^64/2+1. int32 will always hold 2^32 values.
Edit : Ignore my answer, I didn't see C#. My answer was intended for C and C++. I've never used C#
You can use a lambda expression, e.g:
sales['time_hour'] = sales.timestamp.apply(lambda x: x.hour)
Using DISTINCT will work
SELECT GROUP_CONCAT(DISTINCT(categories) SEPARATOR ' ') FROM table
REf:- this
For C++, there are various type-safe enum techniques available, and some of those (such as the proposed-but-never-submitted Boost.Enum) include support for getting the size of a enum.
The simplest approach, which works in C as well as C++, is to adopt a convention of declaring a ...MAX value for each of your enum types:
enum Folders { FA, FB, FC, Folders_MAX = FC };
ContainerClass *m_containers[Folders_MAX + 1];
....
m_containers[FA] = ...; // etc.
Edit: Regarding { FA, FB, FC, Folders_MAX = FC}
versus {FA, FB, FC, Folders_MAX]
: I prefer setting the ...MAX value to the last legal value of the enum for a few reasons:
Folders_MAX
gives the maximum possible enum value).Folders_MAX = FC
stands out from other entries out a bit more (making it a bit harder to accidentally add enum values without updating the max value, a problem Martin York referenced).switch (folder) { case FA: ...; case FB: ...; // Oops, forgot FC! }
I have the same error only on the production build. In development was all right, no warning.
The problem was a comment line
ERROR
return ( // comment
<div>foo</div>
)
OK
// comment
return (
<div>foo</div>
)
Pull the datetime value down as a string and do a DateTime.ParseExact(value, "ddd MMM dd hh:mm:ss yyyy", culture, styles);
You would just need to set the date format up for the date you are returning from the database. Most likely it's yyyy-MM-dd HH:mm:ss
. At least is is for me.
Check here more info on the DateTime.ParseExact
// acos(0.0) will return value of pi/2, inverse of cos(0) is pi/2
double pi = 2 * acos(0.0);
int n; // upto 6 digit
scanf("%d",&n); //precision with which you want the value of pi
printf("%.*lf\n",n,pi); // * will get replaced by n which is the required precision
The other answers here are useful but they don't cover how to access Pacific specifically - here you go:
public static DateTime GmtToPacific(DateTime dateTime)
{
return TimeZoneInfo.ConvertTimeFromUtc(dateTime,
TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time"));
}
Oddly enough, although "Pacific Standard Time" normally means something different from "Pacific Daylight Time," in this case it refers to Pacific time in general. In fact, if you use FindSystemTimeZoneById
to fetch it, one of the properties available is a bool telling you whether that timezone is currently in daylight savings or not.
You can see more generalized examples of this in a library I ended up throwing together to deal with DateTimes I need in different TimeZones based on where the user is asking from, etc:
https://github.com/b9chris/TimeZoneInfoLib.Net
This won't work outside of Windows (for example Mono on Linux) since the list of times comes from the Windows Registry:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones\
Underneath that you'll find keys (folder icons in Registry Editor); the names of those keys are what you pass to FindSystemTimeZoneById
. On Linux you have to use a separate Linux-standard set of timezone definitions, which I've not adequately explored.
Like @ckpepper02 said, the body content:url option works well. I found however that if you modify it slightly you can just use it to add a header image of sorts using the :before pseudo element as follows.
@media print {
body:before { content: url(img/printlogo.png);}
}
That will slip the image at the top of the page, and from my limited testing, it works in Chrome and the IE9
-hanz
One caveat! If you want to compose this via OR or AND you cannot use it in this form:
-myfield:*
but you must use
(*:* NOT myfield:*)
This form is perfectly composable. Apparently SOLR will expand the first form to the second, but only when it is a top node. Hope this saves you some time!
Seems to work here:
>>> a=[[1,1],[2,1],[3,1]]
>>> a
[[1, 1], [2, 1], [3, 1]]
>>> a[1]
[2, 1]
>>> a[1][0]
2
>>> a[1][1]
1
Yes, it is called Short-circuit Evaluation.
If the validity of the boolean statement can be assured after part of the statement, the rest is not evaluated.
This is very important when some of the statements have side-effects.
Number only regex (Updated)
var reg = new RegExp('[^0-9]','g');
For me This was the solution on macOS ReInstall the psql
brew install postgres
Start PostgreSQL server
pg_ctl -D /usr/local/var/postgres start
Initialize DB
initdb /usr/local/var/postgres
If this command throws an error the rm the old database file and re-run the above command
rm -r /usr/local/var/postgres
Create a new database
createdb postgres_test
psql -W postegres_test
You will be logged into this db and can create a user in here to login
Here's one way to do it:
if not any(d['main_color'] == 'red' for d in a):
# does not exist
The part in parentheses is a generator expression that returns True
for each dictionary that has the key-value pair you are looking for, otherwise False
.
If the key could also be missing the above code can give you a KeyError
. You can fix this by using get
and providing a default value. If you don't provide a default value, None
is returned.
if not any(d.get('main_color', default_value) == 'red' for d in a):
# does not exist
Date d=new Date(new Date().getTime()+28800000);
String s=new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(d);
HH will return 0-23 for hours.
kk will return 1-24 for hours.
See more here: Customizing Formats
use method setIs24HourView(Boolean is24HourView) to set time picker to set 24 hour view.
I also found the apache commons IOUtils
class , so :
InputStreamReader isr = new InputStreamReader(IOUtils.toInputStream(myString));
Just add these to libraries to your project:
<link href="https://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.min.css" rel="stylesheet"></link>
<script src="https://code.jquery.com/ui/1.10.2/jquery-ui.min.js"></script>
Save and reload. You're good to go.
import React from 'react';
class Counter extends React.Component{
state = {
count: 0,
};
formatCount() {
const {count} = this.state;
// use a return statement here, it is a importent,
return count === 0 ? 'Zero' : count;
}
render() {
return(
<React.Fragment>
<span>{this.formatCount()}</span>
<button type="button" className="btn btn-primary">Increment</button>
</React.Fragment>
);
}
}
export default Counter;
Zoom level 0 is the most zoomed out zoom level available and each integer step in zoom level halves the X and Y extents of the view and doubles the linear resolution.
Google Maps was built on a 256x256 pixel tile system where zoom level 0 was a 256x256 pixel image of the whole earth. A 256x256 tile for zoom level 1 enlarges a 128x128 pixel region from zoom level 0.
As correctly stated by bkaid, the available zoom range depends on where you are looking and the kind of map you are using:
Note that these values are for the Google Static Maps API which seems to give one more zoom level than the Javascript API. It appears that the extra zoom level available for Static Maps is just an upsampled version of the max-resolution image from the Javascript API.
Google Maps uses a Mercator projection so the scale varies substantially with latitude. A formula for calculating the correct scale based on latitude is:
meters_per_pixel = 156543.03392 * Math.cos(latLng.lat() * Math.PI / 180) / Math.pow(2, zoom)
Formula is from Chris Broadfoot's comment.
Google Maps basics
Zoom Level - zoom
0 - 19
0 lowest zoom (whole world)
19 highest zoom (individual buildings, if available) Retrieve current zoom level using mapObject.getZoom()
What you're looking for are the scales for each zoom level. Use these:
20 : 1128.497220
19 : 2256.994440
18 : 4513.988880
17 : 9027.977761
16 : 18055.955520
15 : 36111.911040
14 : 72223.822090
13 : 144447.644200
12 : 288895.288400
11 : 577790.576700
10 : 1155581.153000
9 : 2311162.307000
8 : 4622324.614000
7 : 9244649.227000
6 : 18489298.450000
5 : 36978596.910000
4 : 73957193.820000
3 : 147914387.600000
2 : 295828775.300000
1 : 591657550.500000
Yes, you can do this, but I doubt that it would improve performances, unless your query has a real large latency.
You could do:
UPDATE table SET posX=CASE
WHEN id=id[1] THEN posX[1]
WHEN id=id[2] THEN posX[2]
...
ELSE posX END, posY = CASE ... END
WHERE id IN (id[1], id[2], id[3]...);
The total cost is given more or less by: NUM_QUERIES * ( COST_QUERY_SETUP + COST_QUERY_PERFORMANCE ). This way, you knock down a bit on NUM_QUERIES, but COST_QUERY_PERFORMANCE goes up bigtime. If COST_QUERY_SETUP is really huge (e.g., you're calling some network service which is real slow) then, yes, you might still end up on top.
Otherwise, I'd try with indexing on id, or modifying the architecture.
In MySQL I think you could do this more easily with a multiple INSERT ON DUPLICATE KEY UPDATE (but am not sure, never tried).
Assuming the MyEjbProject is not another Maven Project you own or want to build with maven, you could use system dependencies to link to the existing jar file of the project like so
<project>
...
<dependencies>
<dependency>
<groupId>yourgroup</groupId>
<artifactId>myejbproject</artifactId>
<version>2.0</version>
<scope>system</scope>
<systemPath>path/to/myejbproject.jar</systemPath>
</dependency>
</dependencies>
...
</project>
That said it is usually the better (and preferred way) to install the package to the repository either by making it a maven project and building it or installing it the way you already seem to do.
If they are, however, dependent on each other, you can always create a separate parent project (has to be a "pom" project) declaring the two other projects as its "modules". (The child projects would not have to declare the third project as their parent). As a consequence you'd get a new directory for the new parent project, where you'd also quite probably put the two independent projects like this:
parent
|- pom.xml
|- MyEJBProject
| `- pom.xml
`- MyWarProject
`- pom.xml
The parent project would get a "modules" section to name all the child modules. The aggregator would then use the dependencies in the child modules to actually find out the order in which the projects are to be built)
<project>
...
<artifactId>myparentproject</artifactId>
<groupId>...</groupId>
<version>...</version>
<packaging>pom</packaging>
...
<modules>
<module>MyEJBModule</module>
<module>MyWarModule</module>
</modules>
...
</project>
That way the projects can relate to each other but (once they are installed in the local repository) still be used independently as artifacts in other projects
Finally, if your projects are not in related directories, you might try to give them as relative modules:
filesystem
|- mywarproject
| `pom.xml
|- myejbproject
| `pom.xml
`- parent
`pom.xml
now you could just do this (worked in maven 2, just tried it):
<!--parent-->
<project>
<modules>
<module>../mywarproject</module>
<module>../myejbproject</module>
</modules>
</project>
The only reason that the linter complains about using setState({..})
in componentDidMount
and componentDidUpdate
is that when the component render the setState immediately causes the component to re-render.
But the most important thing to note: using it inside these component's lifecycles is not an anti-pattern in React.
Please take a look at this issue. you will understand more about this topic. Thanks for reading my answer.
By subquery, it should work:
SELECT distinct(Category) from MonitoringJob where Category in(select Category from MonitoringJob order by CreationDate desc);
Do the following:
Dim dataTable1 As New DataTable
dataTable1.Columns.Add("FECHA")
dataTable1.Columns.Add("TT")
dataTable1.Columns.Add("DESCRIPCION")
dataTable1.Columns.Add("No. DOC")
dataTable1.Columns.Add("DEBE")
dataTable1.Columns.Add("HABER")
dataTable1.Columns.Add("SALDO")
For Each line As String In System.IO.File.ReadAllLines(objetos.url)
dataTable1.Rows.Add(line.Split(","))
Next
It means you have a null reference somewhere in there. Can you debug the app and stop the debugger when it gets here and investigate? Probably img1
is null or ConfigurationManager.AppSettings.Get("Url")
is returning null.
If it is a list, you can also use AddRange method.
var listB = new List<int>{3, 4, 5};
var listA = new List<int>{1, 2, 3, 4, 5};
listA.AddRange(listB); // listA now has elements of listB also.
If you need new list (and exclude the duplicate), you can use Union
var listB = new List<int>{3, 4, 5};
var listA = new List<int>{1, 2, 3, 4, 5};
var listFinal = listA.Union(listB);
If you need new list (and include the duplicate), you can use Concat
var listB = new List<int>{3, 4, 5};
var listA = new List<int>{1, 2, 3, 4, 5};
var listFinal = listA.Concat(listB);
If you need common items, you can use Intersect.
var listB = new List<int>{3, 4, 5};
var listA = new List<int>{1, 2, 3, 4};
var listFinal = listA.Intersect(listB); //3,4
.service-small option {
font-size: 14px;
padding: 5px;
background: #5c5c5c;
}
I think it because you used .styled-select in start of the class code.
The common practice is to use the dummy variable _
(single underscore), as many have indicated here before.
However, to avoid collisions with other uses of that variable name (see this response) it might be a better practice to use __
(double underscore) instead as a throwaway variable, as pointed by ncoghlan. E.g.:
x, __ = func()
Here are some thoughts and ideas:
Use ROM more creatively.
Store anything you can in ROM. Instead of calculating things, store look-up tables in ROM. (Make sure your compiler is outputting your look-up tables to the read-only section! Print out memory addresses at runtime to check!) Store your interrupt vector table in ROM. Of course, run some tests to see how reliable your ROM is compared to your RAM.
Use your best RAM for the stack.
SEUs in the stack are probably the most likely source of crashes, because it is where things like index variables, status variables, return addresses, and pointers of various sorts typically live.
Implement timer-tick and watchdog timer routines.
You can run a "sanity check" routine every timer tick, as well as a watchdog routine to handle the system locking up. Your main code could also periodically increment a counter to indicate progress, and the sanity-check routine could ensure this has occurred.
Implement error-correcting-codes in software.
You can add redundancy to your data to be able to detect and/or correct errors. This will add processing time, potentially leaving the processor exposed to radiation for a longer time, thus increasing the chance of errors, so you must consider the trade-off.
Remember the caches.
Check the sizes of your CPU caches. Data that you have accessed or modified recently will probably be within a cache. I believe you can disable at least some of the caches (at a big performance cost); you should try this to see how susceptible the caches are to SEUs. If the caches are hardier than RAM then you could regularly read and re-write critical data to make sure it stays in cache and bring RAM back into line.
Use page-fault handlers cleverly.
If you mark a memory page as not-present, the CPU will issue a page fault when you try to access it. You can create a page-fault handler that does some checking before servicing the read request. (PC operating systems use this to transparently load pages that have been swapped to disk.)
Use assembly language for critical things (which could be everything).
With assembly language, you know what is in registers and what is in RAM; you know what special RAM tables the CPU is using, and you can design things in a roundabout way to keep your risk down.
Use objdump
to actually look at the generated assembly language, and work out how much code each of your routines takes up.
If you are using a big OS like Linux then you are asking for trouble; there is just so much complexity and so many things to go wrong.
Remember it is a game of probabilities.
A commenter said
Every routine you write to catch errors will be subject to failing itself from the same cause.
While this is true, the chances of errors in the (say) 100 bytes of code and data required for a check routine to function correctly is much smaller than the chance of errors elsewhere. If your ROM is pretty reliable and almost all the code/data is actually in ROM then your odds are even better.
Use redundant hardware.
Use 2 or more identical hardware setups with identical code. If the results differ, a reset should be triggered. With 3 or more devices you can use a "voting" system to try to identify which one has been compromised.
On OpenSUSE 15.3 systemd log reported this error (insmod suggestion was unhelpful).
Feb 18 08:36:38 vagrant-openSUSE-Leap dockerd[20635]: iptables v1.6.2: can't initialize iptables table `nat': Table does not exist (do you need to insmod?)
REBOOT fixed the problem
What you saw in Firefox was not the actual request; note that the HTTP method is OPTIONS, not POST. It was actually the 'pre-flight' request that the browser makes to determine whether a cross-domain AJAX request should be allowed:
The Access-Control-Request-Headers header in the pre-flight request includes the list of headers in the actual request. The server is then expected to report back whether these headers are supported in this context or not, before the browser submits the actual request.
The EXCEL and OLED DB connection managers use the parameter names 0 and 1.
I was using a oledb connection and wasted couple of hours trying to figure out the reason why the query was not working or taking the parameters. the above explanation helped a lot Thanks a lot.
I would like to suggest a much cleaner way. This will be useful when we have multiple storyboards
1.Create a structure with all your storyboards
struct Storyboard {
static let main = "Main"
static let login = "login"
static let profile = "profile"
static let home = "home"
}
2. Create a UIStoryboard extension like this
extension UIStoryboard {
@nonobjc class var main: UIStoryboard {
return UIStoryboard(name: Storyboard.main, bundle: nil)
}
@nonobjc class var journey: UIStoryboard {
return UIStoryboard(name: Storyboard.login, bundle: nil)
}
@nonobjc class var quiz: UIStoryboard {
return UIStoryboard(name: Storyboard.profile, bundle: nil)
}
@nonobjc class var home: UIStoryboard {
return UIStoryboard(name: Storyboard.home, bundle: nil)
}
}
Give the storyboard identifier as the class name, and use the below code to instantiate
let loginVc = UIStoryboard.login.instantiateViewController(withIdentifier: "\(LoginViewController.self)") as! LoginViewController
You can use:
SELECT CONVERT(datetime, '24.04.2012', 103) AS Date
Reference: CAST and CONVERT (Transact-SQL)
Single line comment
Ctrl + 1
Multi-line comment select the lines to be commented
Ctrl + 4
Unblock Multi-line comment
Ctrl + 5
The supplied host is not resolving for me (custom DNS or self configured host?) so I can only hazard to guess.
But as you are requesting the resources over SSL it is likely the certificate is invalid. Either it is self-signed and has not been added to your browser/OS exceptions or it is otherwise invalid.
Try the URI directly in the same browser and inspect the certificate.
Edit: this is in no way related to jQuery, JavaScript or CSS directly.
This is a barebones look at what I've done to float one image over another.
img {_x000D_
position: absolute;_x000D_
top: 25px;_x000D_
left: 25px;_x000D_
}_x000D_
.imgA1 {_x000D_
z-index: 1;_x000D_
}_x000D_
.imgB1 {_x000D_
z-index: 3;_x000D_
}
_x000D_
<img class="imgA1" src="https://placehold.it/200/333333">_x000D_
<img class="imgB1" src="https://placehold.it/100">
_x000D_
What is wrong with List.Find ??
I think we need more information on what you've done, and why it fails, before we can provide truly helpful answers.
Realize this is an old thread but here are a couple other ways (works with EAP 6.4):
# jboss-cli.sh -c --controller=127.0.0.1:9999 'version'
JBoss Admin Command-line Interface
JBOSS_HOME: /opt/AAS/latest/jboss
JBoss AS release: 7.5.14.Final-redhat-2 "Janus"
JBoss AS product: EAP 6.4.14.GA
# more /opt/jboss/.installation/identity.conf
patches=
cumulative-patch-id=jboss-eap-6.4.14.CP
installed-patches=jboss-eap-6.4.1.CP,jboss-eap-6.4.2.CP,jboss-eap-6.4.3.CP,jboss-eap-6.4.4.CP,jboss-eap-6.4.5.CP,jboss-eap-6.4.6.CP,jboss-eap-6.4.7.CP,jboss-eap-6.4.8.CP,jboss-eap-6.4.9.CP,
jboss-eap-6.4.10.CP,jboss-eap-6.4.11.CP,jboss-eap-6.4.12.CP,jboss-eap-6.4.13.CP,jboss-eap-6.4.14.CP
The issue is that even though we add a folder to skip list it will be deleted if it does not exist.
The solution is to add both the destination and the source folder with full path.
I will try to explain the different scenarios and what happens below, based on my experience.
Starting folder structure:
d:\Temp\source\1.txt
d:\Temp\source\2\2.txt
Command:
robocopy D:\Temp\source D:\Temp\dest /MIR
This will copy over all the files and folders that are missing and deletes all the files and folders that cannot be found in the source
Let's add a new folder and then add it to the command to skip it.
New structure:
d:\Temp\source\1.txt
d:\Temp\source\2\2.txt
d:\Temp\source\3\3.txt
Command:
robocopy D:\Temp\source D:\Temp\dest /MIR /XD "D:\Temp\source\3"
If I add /XD with the source folder and run the command it all seems good the command it wont copy it over.
Now add a folder to the destination to get this setup:
d:\Temp\source\1.txt
d:\Temp\source\2\2.txt
d:\Temp\source\3\3.txt
d:\Temp\dest\1.txt
d:\Temp\dest\2\2.txt
d:\Temp\dest\3\4.txt
If I run the command it is still fine, 4.txt stays there 3.txt is not copied over. All is fine.
But, if I delete the source folder "d:\Temp\source\3" then the destination folder and the file are deleted even though it is on the skip list
1 D:\Temp\source\
*EXTRA Dir -1 D:\Temp\dest\3\
*EXTRA File 4 4.txt
1 D:\Temp\source\2\
If I change the command to skip the destination folder instead then the folder is not deleted, when the folder is missing from the source.
robocopy D:\Temp\source D:\Temp\dest /MIR /XD "D:\Temp\dest\3"
On the other hand if the folder exists and there are files it will copy them over and delete them:
1 D:\Temp\source\3\
*EXTRA File 4 4.txt
100% New File 4 3.txt
To make sure the folder is always skipped and no files are copied over even if the source or destination folder is missing we have to add both to the skip list:
robocopy D:\Temp\source D:\Temp\dest /MIR /XD "d:\Temp\source\3" "D:\Temp\dest\3"
After this no matters if the source folder is missing or the destination folder is missing, robocopy will leave it as it is.
You need to retrieve and disect the information into what you need.
while($row = mysql_fetch_array($result)) {
echo "img src='",$row['filename'],"' width='175' height='200' />";
}
drop procedure if exists doWhile;
DELIMITER //
CREATE PROCEDURE doWhile()
BEGIN
DECLARE i INT DEFAULT 2376921001;
WHILE (i <= 237692200) DO
INSERT INTO `mytable` (code, active, total) values (i, 1, 1);
SET i = i+1;
END WHILE;
END;
//
CALL doWhile();
You should use ant -version
command instead.
The -v
option is equivalent of -verbose
option.
See Command-line Options Summary
console.log(typeof json_data !== 'undefined'
? json_data.length : 'There is no spoon.');
...or more simply...
console.log(json_data ? json_data.length : 'json_data is null or undefined');
For completeness, the answer to Asp.Net Core tag in web.config causes failure may also be the solution to the problem here. If the .NET Core Windows Server Hosting bundle is not installed then IIS cannot recognize the aspNetCore section in web.config. https://docs.microsoft.com/en-us/aspnet/core/host-and-deploy/iis/?view=aspnetcore-3.1#install-the-net-core-hosting-bundle claims to be a direct download to the current version.
try adding the permission outside the application tag of the manifest in addition to the above mentioned answers of changing localhost to 10.0.2.2:8080
I always just use sc.exe (see http://support.microsoft.com/kb/251192). It should be installed on XP from SP1, and if it's not in your flavor of Vista, you can download load it with the Vista resource kit.
I haven't done anything too complicated with Java, but using either a fully qualified command line argument (x:\java.exe ....) or creating a script with Ant to include depencies and set parameters works fine for me.
When you just give make, it makes the first rule in your makefile, i.e "all". You have specified that "all" depends on "hello", which depends on main.o, factorial.o and hello.o. So 'make' tries to see if those files are present.
If they are present, 'make' sees if their dependencies, e.g. main.o has a dependency main.c, have changed. If they have changed, make rebuilds them, else skips the rule. Similarly it recursively goes on building the files that have changed and finally runs the top most command, "all" in your case to give you a executable, 'hello' in your case.
If they are not present, make blindly builds everything under the rule.
Coming to your problem, it isn't an error but 'make' is saying that every dependency in your makefile is up to date and it doesn't need to make anything!
public class Shift {
public static void main(String[] args) {
Byte b = Byte.parseByte("00101011",2);
System.out.println(b);
byte val = b.byteValue();
Byte shifted = new Byte((byte) (val >> 2));
System.out.println(shifted);
// often overloked are the methods of Integer
int i = Integer.parseInt("00101011",2);
System.out.println( Integer.toBinaryString(i));
i >>= 2;
System.out.println( Integer.toBinaryString(i));
}
}
Output:
43
10
101011
1010
The "star sign" is only meaningful if there is something in front of it. If there isn't the tool (grep in this case) may just treat it as an error. For example:
'*xyz' is meaningless
'a*xyz' means zero or more occurrences of 'a' followed by xyz
Honestly, it's trivial to write a program to compare the performance:
#include <ctime>
#include <iostream>
namespace {
class empty { }; // even empty classes take up 1 byte of space, minimum
}
int main()
{
std::clock_t start = std::clock();
for (int i = 0; i < 100000; ++i)
empty e;
std::clock_t duration = std::clock() - start;
std::cout << "stack allocation took " << duration << " clock ticks\n";
start = std::clock();
for (int i = 0; i < 100000; ++i) {
empty* e = new empty;
delete e;
};
duration = std::clock() - start;
std::cout << "heap allocation took " << duration << " clock ticks\n";
}
It's said that a foolish consistency is the hobgoblin of little minds. Apparently optimizing compilers are the hobgoblins of many programmers' minds. This discussion used to be at the bottom of the answer, but people apparently can't be bothered to read that far, so I'm moving it up here to avoid getting questions that I've already answered.
An optimizing compiler may notice that this code does nothing, and may optimize it all away. It is the optimizer's job to do stuff like that, and fighting the optimizer is a fool's errand.
I would recommend compiling this code with optimization turned off because there is no good way to fool every optimizer currently in use or that will be in use in the future.
Anybody who turns the optimizer on and then complains about fighting it should be subject to public ridicule.
If I cared about nanosecond precision I wouldn't use std::clock()
. If I wanted to publish the results as a doctoral thesis I would make a bigger deal about this, and I would probably compare GCC, Tendra/Ten15, LLVM, Watcom, Borland, Visual C++, Digital Mars, ICC and other compilers. As it is, heap allocation takes hundreds of times longer than stack allocation, and I don't see anything useful about investigating the question any further.
The optimizer has a mission to get rid of the code I'm testing. I don't see any reason to tell the optimizer to run and then try to fool the optimizer into not actually optimizing. But if I saw value in doing that, I would do one or more of the following:
Add a data member to empty
, and access that data member in the loop; but if I only ever read from the data member the optimizer can do constant folding and remove the loop; if I only ever write to the data member, the optimizer may skip all but the very last iteration of the loop. Additionally, the question wasn't "stack allocation and data access vs. heap allocation and data access."
Declare e
volatile
, but volatile
is often compiled incorrectly (PDF).
Take the address of e
inside the loop (and maybe assign it to a variable that is declared extern
and defined in another file). But even in this case, the compiler may notice that -- on the stack at least -- e
will always be allocated at the same memory address, and then do constant folding like in (1) above. I get all iterations of the loop, but the object is never actually allocated.
Beyond the obvious, this test is flawed in that it measures both allocation and deallocation, and the original question didn't ask about deallocation. Of course variables allocated on the stack are automatically deallocated at the end of their scope, so not calling delete
would (1) skew the numbers (stack deallocation is included in the numbers about stack allocation, so it's only fair to measure heap deallocation) and (2) cause a pretty bad memory leak, unless we keep a reference to the new pointer and call delete
after we've got our time measurement.
On my machine, using g++ 3.4.4 on Windows, I get "0 clock ticks" for both stack and heap allocation for anything less than 100000 allocations, and even then I get "0 clock ticks" for stack allocation and "15 clock ticks" for heap allocation. When I measure 10,000,000 allocations, stack allocation takes 31 clock ticks and heap allocation takes 1562 clock ticks.
Yes, an optimizing compiler may elide creating the empty objects. If I understand correctly, it may even elide the whole first loop. When I bumped up the iterations to 10,000,000 stack allocation took 31 clock ticks and heap allocation took 1562 clock ticks. I think it's safe to say that without telling g++ to optimize the executable, g++ did not elide the constructors.
In the years since I wrote this, the preference on Stack Overflow has been to post performance from optimized builds. In general, I think this is correct. However, I still think it's silly to ask the compiler to optimize code when you in fact do not want that code optimized. It strikes me as being very similar to paying extra for valet parking, but refusing to hand over the keys. In this particular case, I don't want the optimizer running.
Using a slightly modified version of the benchmark (to address the valid point that the original program didn't allocate something on the stack each time through the loop) and compiling without optimizations but linking to release libraries (to address the valid point that we don't want to include any slowdown caused by linking to debug libraries):
#include <cstdio>
#include <chrono>
namespace {
void on_stack()
{
int i;
}
void on_heap()
{
int* i = new int;
delete i;
}
}
int main()
{
auto begin = std::chrono::system_clock::now();
for (int i = 0; i < 1000000000; ++i)
on_stack();
auto end = std::chrono::system_clock::now();
std::printf("on_stack took %f seconds\n", std::chrono::duration<double>(end - begin).count());
begin = std::chrono::system_clock::now();
for (int i = 0; i < 1000000000; ++i)
on_heap();
end = std::chrono::system_clock::now();
std::printf("on_heap took %f seconds\n", std::chrono::duration<double>(end - begin).count());
return 0;
}
displays:
on_stack took 2.070003 seconds
on_heap took 57.980081 seconds
on my system when compiled with the command line cl foo.cc /Od /MT /EHsc
.
You may not agree with my approach to getting a non-optimized build. That's fine: feel free modify the benchmark as much as you want. When I turn on optimization, I get:
on_stack took 0.000000 seconds
on_heap took 51.608723 seconds
Not because stack allocation is actually instantaneous but because any half-decent compiler can notice that on_stack
doesn't do anything useful and can be optimized away. GCC on my Linux laptop also notices that on_heap
doesn't do anything useful, and optimizes it away as well:
on_stack took 0.000003 seconds
on_heap took 0.000002 seconds
For some reason, the replace works only with one string each time. I had a string like this "Test MSP" and I want to leave only one space.
I used the approach that @Farhan did, but with some modifications:
CREATE FUNCTION ReplaceAll
(
@OriginalString varchar(8000),
@StringToRemove varchar(20),
@StringToPutInPlace varchar(20)
)
RETURNS varchar(8000)
AS
BEGIN
declare @ResultStr varchar(8000)
set @ResultStr = @OriginalString
while charindex(@StringToRemove, @ResultStr) > 0
set @ResultStr = replace(@ResultStr, @StringToRemove, @StringToPutInPlace)
return @ResultStr
END
Then I run my update like this
UPDATE tbTest SET Description = dbo.ReplaceAll(Description, ' ', ' ') WHERE ID = 14225
Then I got this result: Test MSP
Posting here if in case someone needs it as I did.
Running on: Microsoft SQL Server 2016 (SP2)
Maybe you mean
select x
from some_table
where some_column is null or some_column = ''
but I can't tell since you didn't really ask a question.
In case the WebSocket server initiative disconnects the
ws
link after a few minutes there no messages sent between the server and client.
client sends a custom ping
message, to keep alive by using the keepAlive
function
server ignore the ping
message and response a custom pong
message
var timerID = 0;
function keepAlive() {
var timeout = 20000;
if (webSocket.readyState == webSocket.OPEN) {
webSocket.send('');
}
timerId = setTimeout(keepAlive, timeout);
}
function cancelKeepAlive() {
if (timerId) {
clearTimeout(timerId);
}
}
As a follow on, you could select "all nodes with a particular attribute" like this:
//*[@id='4']
The best approach to use yum and update your devtoolset is to utilize the CentOS SCLo RH Testing repository.
yum install centos-release-scl-rh
yum --enablerepo=centos-sclo-rh-testing install devtoolset-7-gcc devtoolset-7-gcc-c++
Many additional packages are also available, to see them all
yum --enablerepo=centos-sclo-rh-testing list devtoolset-7*
You can use this method to install any dev tool version, just swap the 7 for your desired version. devtoolset-6-gcc, devtoolset-5-gcc etc.
Based on @user's answer, you can just add this extension anywhere in your app code and have your selection color directly in storyboard editor for every cells of your app :
@IBDesignable extension UITableViewCell {
@IBInspectable var selectedColor: UIColor? {
set {
if let color = newValue {
selectedBackgroundView = UIView()
selectedBackgroundView!.backgroundColor = color
} else {
selectedBackgroundView = nil
}
}
get {
return selectedBackgroundView?.backgroundColor
}
}
}
I have the problem because I updated Java version.
The following steps work for me:
- Run
\Tomcat\bin\tomcat7w.exe
- Confirm "Startup" tab -> "Mode" choose "jvm"
- "Java" tab -> update "Java Virtual Machine" path to new version path
- Restart Tomcat
Done.
They pretty much got it there... just like a checkbox, all you have to do is add the attribute checked="checked" like so:
<input type="radio" checked="checked">
...and you got it.
Cheers!
This is supposedly because you trying to make cross-domain request, or something that is clarified as it.
You could try adding header('Access-Control-Allow-Origin: *');
to the requested file.
Also, such problem is sometimes occurs on server-sent events implementation in case of using event-source
or XHR polling
in IE 8-10 (which confused me first time).
A minimalistic example to quickly test the TTS system:
private TextToSpeech textToSpeechSystem;
@Override
protected void onStart() {
super.onStart();
textToSpeechSystem = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
String textToSay = "Hello world, this is a test message!";
textToSpeechSystem.speak(textToSay, TextToSpeech.QUEUE_ADD, null);
}
}
});
}
If you don't use localized messages textToSpeechSystem.setLanguage(..)
is important as well, since your users probably don't all have English set as their default language so the pronunciation of the words will be wrong. But for testing TTS in general this snippet is enough
Related links: https://developer.android.com/reference/android/speech/tts/TextToSpeech
pragma is your best bet:
<meta http-equiv="Pragma" content="no-cache">
The easiest way is
https://graph.facebook.com/me?fields=id&access_token="xxxxx"
then you will get json response which contains only userid.
The following simpler shell script worked for me.
#!/bin/bash
for i in `psql -U $1 -qt -c "select tablename from pg_tables where schemaname='$2'"`
do
psql -U $1 -c "alter table $2.$i set schema $3"
done
Where input $1 - username (database) $2 = existing schema $3 = to new schema.
You should use glob.
glob('*.xml')
More about using glob and advanced filtering:
http://domexception.blogspot.fi/2013/08/php-using-functional-programming-for.html
Use <div contenteditable="true">
(supported well) with storing to <input type="hidden">
.
HTML:
<div id="multilineinput" contenteditable="true"></div>
<input type="hidden" id="detailsfield" name="detailsfield">
js (using jQuery)
$("#multilineinput").on('keyup',function(e) {
$("#detailsfield").val($(this).text()); //store content to input[type=hidden]
});
//optional - one line but wrap it
$("#multilineinput").on('keypress',function(e) {
if(e.which == 13) { //on enter
e.preventDefault(); //disallow newlines
// here comes your code to submit
}
});
=iferror(1/ (1/ H15+G16-F16 ), "")
this way avoids repeating the central calculation (which can often be much longer or more processor hungry than the one you have here...
enjoy
I don't think it is possible to share a database link between more than one user but not all. They are either private (for one user only) or public (for all users).
A good way around this is to create a view in SCHEMA_B that exposes the table you want to access through the database link. This will also give you good control over who is allowed to select from the database link, as you can control the access to the view.
Do like this:
create database link db_link... as before;
create view mytable_view as select * from mytable@db_link;
grant select on mytable_view to myuser;
Late to the party, but I think this is actually the most elegant. Use the WORD JOINER Unicode character ⁠ on either side of your hyphen, or em dash, or any character.
So, like so:
⁠—⁠
This will join the symbol on both ends to its neighbors (without adding a space) and prevent line breaking.
The case class construct in Scala can also be seen as a convenience to remove some boilerplate.
When constructing a case class Scala gives you the following.
apply
method that you are able to use as a factory method. You get the syntactic sugar advantage of not having to use the new keyword.
Because the class is immutable you get accessors, which are just the variables (or properties) of the class but no mutators (so no ability to change the variables). The constructor parameters are automatically available to you as public read only fields. Much nicer to use than Java bean construct.
hashCode
, equals
, and toString
methods by default and the equals
method compares an object structurally. A copy
method is generated to be able to clone an object (with some fields having new values provided to the method). The biggest advantage as has been mentioned previously is the fact that you can pattern match on case classes. The reason for this is because you get the unapply
method which lets you deconstruct a case class to extract its fields.
In essence what you are getting from Scala when creating a case class (or a case object if your class takes no arguments) is a singleton object which serves the purpose as a factory and as an extractor .
About promise composition vs. Rxjs, as this is a frequently asked question, you can refer to a number of previously asked questions on SO, among which :
Basically, flatMap
is the equivalent of Promise.then
.
For your second question, do you want to replay values already emitted, or do you want to process new values as they arrive? In the first case, check the publishReplay
operator. In the second case, standard subscription is enough. However you might need to be aware of the cold. vs. hot dichotomy depending on your source (cf. Hot and Cold observables : are there 'hot' and 'cold' operators? for an illustrated explanation of the concept)
Update November 2015:
Update December 2013:
Lars Vogel just published on his blog:
(December 10, 2013)
We conducted a user survey if users want to have line numbers activated in text editors in the Eclipse IDE by default.
The response was very clear:
YES : 80.07% (1852 responses)
NO : 19.93% (461 responses)
Total : 2313
Skipped: 15
With Bug 421313, Review - Line number should be activated by default, we enabled it for the Eclipse SDK build, I assume other Eclipse packages will follow.
Update August 2014
Line number default length is now 120 (instead of 80) for Eclipse Mars 4.5M1.
See "How to customize Eclipse's text editor code formating".
Original answer (March 2009)
To really have it by default, you can write a script which ensure, before launching eclipse, that:
[workspace]\.metadata\.plugins\org.eclipse.core.runtime\.settings\org.eclipse.ui.editors.prefs
does contain:
lineNumberRuler=true
(with [workspace]
being the root directory of your eclipse workspace)
Then eclipse will be opened with "line numbers shown 'by default' "
Otherwise, you can also type 'CTRL+1' and then "line", which will give you access to the command "Show line numbers"
(that will switch to option "show line numbers" in the text editors part of the option.
Or you can just type "numb" in Windows Preferences to access to the Text Editor part:
Picture from "How to display line numbers in Eclipse" of blog "Mkyong.com"
While the answer given by Paul H shows the essential part, it is not a complete example. On the other hand the matplotlib example seems rather complicated and does not show how to use days.
So for everyone in need here is a full working example:
from datetime import datetime
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter
myDates = [datetime(2012,1,i+3) for i in range(10)]
myValues = [5,6,4,3,7,8,1,2,5,4]
fig, ax = plt.subplots()
ax.plot(myDates,myValues)
myFmt = DateFormatter("%d")
ax.xaxis.set_major_formatter(myFmt)
## Rotate date labels automatically
fig.autofmt_xdate()
plt.show()
If someone is sniffing your plain-text HTTP traffic (or cache/cookies) for passwords just turning the password into a hash won't help - The hash password can be "replayed" just as well as plain-text. The client would need to hash the password with something somewhat random (like the date and time) See the section on "AUTH CRAM-MD5" here: http://www.fehcom.de/qmail/smtpauth.html
I go with Mark Longair's solution and comments and recommend anyone reads those before acting, but I'd suggest the emphasis should be on
git branch -f <branchname> <commit>
Here is a scenario where I have needed to do this.
Develop on the wrong branch and hence need to reset it.
Cleanly develop and release some software.
Mistake: Accidentally stay on the release branch while developing further.
"OH NO! I accidentally developed on the release branch." The workspace is maybe cluttered with half changed files that represent work-in-progress and we really don't want to touch and mess with. We'd just like git to flip a few pointers to keep track of the current state and put that release branch back how it should be.
Create a branch for the development that is up to date holding the work committed so far and switch to it.
git branch development
git checkout development
Now we are in the problem situation and need its solution! Rectify the mistake (of taking the release branch forward with the development) and put the release branch back how it should be.
Correct the release branch to point back to the last real release.
git branch -f release release2
The release branch is now correct again, like this ...
git push -f <remote> <branch>
is well described in another thread, though the word "overwrite" in the title is misleading.
Force "git push" to overwrite remote files
@neilfws's solution works great for data.frame
s, but not for data.table
s since they lack the row.names
property. This approach works for both:
df.expanded <- df[rep(seq(nrow(df)), df$freq), 1:2]
The code for data.table
is a tad cleaner:
# convert to data.table by reference
setDT(df)
df.expanded <- df[rep(seq(.N), freq), !"freq"]
This should solve your problem:
select replace(to_char(a, '90D90'),'.00','')
from
(
select 50 a from dual
union
select 50.57 from dual
union
select 5.57 from dual
union
select 0.35 from dual
union
select 0.4 from dual
);
Give a look also as this SQL Fiddle for test.
for that matters you have to use your SVG as an inline HTML.
say here's your logo.svg code (when you open it on textEditor):
Logo.SVG
<svg width="139" height="100" xmlns="http://www.w3.org/2000/svg">
<!-- Note that I've Added Class Attribute 'logo-img' Here -->
<g transform="translate(-22 -45)" fill="none" fill-rule="evenodd">
<path
d="M158.023 48.118a7.625 7.625 0 01-.266 10.78l-88.11 83.875a7.625 7.625 0 01-10.995-.5l-33.89-38.712a7.625 7.625 0 0111.475-10.045l28.653 32.73 82.353-78.394a7.625 7.625 0 0110.78.266z"
fill="#00000" />
</g>
</svg>
add your desired Class/ID to it (i've added 'logo-img'):
Edited Svg
<svg class="logo-img" width="139" height="100" xmlns="http://www.w3.org/2000/svg">
<!-- Note that I've Added Class Attribute 'logo-img' Here -->
...
</svg>
Now apply Your Css Rules:
CSS
.logo-img path {
fill: #000;
}
Pro
Con
Heres a Stack Snippet
<style>
body {
display: flex;
justify-content: center;
}
.logo-img path {
transition: .5s all linear;
}
.logo-img path {
fill: coral;
}
.logo-img:hover path{
fill: darkblue;
}
</style>
_x000D_
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<svg class="logo-img" width="139" height="100" xmlns="http://www.w3.org/2000/svg">
<!-- Note that I've Added Class Attribute 'logo-img' Here -->
<g transform="translate(-22 -45)" fill="none" fill-rule="evenodd">
<path
d="M158.023 48.118a7.625 7.625 0 01-.266 10.78l-88.11 83.875a7.625 7.625 0 01-10.995-.5l-33.89-38.712a7.625 7.625 0 0111.475-10.045l28.653 32.73 82.353-78.394a7.625 7.625 0 0110.78.266z"
fill="#00000" />
</g>
</svg>
</body>
</html>
_x000D_
Your problem stems from a misunderstanding of the or
operator that is common to people learning programming languages like this. Yes, your immediate problem can be solved by writing x ~= 0 and x ~= 1
, but I'll go into a little more detail about why your attempted solution doesn't work.
When you read x ~=(0 or 1)
or x ~= 0 or 1
it's natural to parse this as you would the sentence "x is not equal to zero or one". In the ordinary understanding of that statement, "x" is the subject, "is not equal to" is the predicate or verb phrase, and "zero or one" is the object, a set of possibilities joined by a conjunction. You apply the subject with the verb to each item in the set.
However, Lua does not parse this based on the rules of English grammar, it parses it in binary comparisons of two elements based on its order of operations. Each operator has a precedence which determines the order in which it will be evaluated. or
has a lower precedence than ~=
, just as addition in mathematics has a lower precedence than multiplication. Everything has a lower precedence than parentheses.
As a result, when evaluating x ~=(0 or 1)
, the interpreter will first compute 0 or 1
(because of the parentheses) and then x ~=
the result of the first computation, and in the second example, it will compute x ~= 0
and then apply the result of that computation to or 1
.
The logical operator or
"returns its first argument if this value is different from nil and false; otherwise, or returns its second argument". The relational operator ~=
is the inverse of the equality operator ==
; it returns true if its arguments are different types (x is a number, right?), and otherwise compares its arguments normally.
Using these rules, x ~=(0 or 1)
will decompose to x ~= 0
(after applying the or
operator) and this will return 'true' if x is anything other than 0, including 1, which is undesirable. The other form, x ~= 0 or 1
will first evaluate x ~= 0
(which may return true or false, depending on the value of x). Then, it will decompose to one of false or 1
or true or 1
. In the first case, the statement will return 1
, and in the second case, the statement will return true
. Because control structures in Lua only consider nil
and false
to be false, and anything else to be true, this will always enter the if
statement, which is not what you want either.
There is no way that you can use binary operators like those provided in programming languages to compare a single variable to a list of values. Instead, you need to compare the variable to each value one by one. There are a few ways to do this. The simplest way is to use De Morgan's laws to express the statement 'not one or zero' (which can't be evaluated with binary operators) as 'not one and not zero', which can trivially be written with binary operators:
if x ~= 1 and x ~= 0 then
print( "X must be equal to 1 or 0" )
return
end
Alternatively, you can use a loop to check these values:
local x_is_ok = false
for i = 0,1 do
if x == i then
x_is_ok = true
end
end
if not x_is_ok then
print( "X must be equal to 1 or 0" )
return
end
Finally, you could use relational operators to check a range and then test that x was an integer in the range (you don't want 0.5, right?)
if not (x >= 0 and x <= 1 and math.floor(x) == x) then
print( "X must be equal to 1 or 0" )
return
end
Note that I wrote x >= 0 and x <= 1
. If you understood the above explanation, you should now be able to explain why I didn't write 0 <= x <= 1
, and what this erroneous expression would return!
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddDbContext<ConfigurationRepository>(options =>
options.UseSqlServer(Configuration.GetConnectionString("SqlConnectionString")));
services.AddScoped<IConfigurationBL, ConfigurationBL>();
services.AddScoped<IConfigurationRepository, ConfigurationRepository>();
}
I used this method works for any number of nested and not require hacking
<?php
$blogCategories = [
'programing' => [
'golang',
'php',
'ruby',
'functional' => [
'Erlang',
'Haskell'
]
],
'bd' => [
'mysql',
'sqlite'
]
];
$it = new RecursiveArrayIterator($blogCategories);
foreach (new RecursiveIteratorIterator($it) as $t) {
$found = $t == 'Haskell';
if ($found) {
break;
}
}
As I don't have access to postgres account (so can't run SHOW config_file
) and my postgres is installed on Windows, none of the answers helped me, so I'm sharing my file location for future Windows readers:
C:\Program Files\PostgreSQL\9.5\data