Asymptotic notation is something you can understand as: how do functions compare when zooming out? (A good way to test this is simply to use a tool like Desmos and play with your mouse wheel). In particular:
f(n) ? o(n)
means: at some point, the more you zoom out, the more f(n)
will be dominated by n
(it will progressively diverge from it).g(n) ? T(n)
means: at some point, zooming out will not change how g(n)
compare to n
(if we remove ticks from the axis you couldn't tell the zoom level).Finally h(n) ? O(n)
means that function h
can be in either of these two categories. It can either look a lot like n
or it could be smaller and smaller than n
when n
increases. Basically, both f(n)
and g(n)
are also in O(n)
.
In computer science, people will usually prove that a given algorithm admits both an upper O
and a lower bound . When both bounds meet that means that we found an asymptotically optimal algorithm to solve that particular problem.
For example, if we prove that the complexity of an algorithm is both in O(n)
and (n)
it implies that its complexity is in T(n)
. That's the definition of T
and it more or less translates to "asymptotically equal". Which also means that no algorithm can solve the given problem in o(n)
. Again, roughly saying "this problem can't be solved in less than n
steps".
An upper bound of O(n)
simply means that even in the worse case, the algorithm will terminate in at most n
steps (ignoring all constant factors, both multiplicative and additive). A lower bound of (n)
means on the opposite that we built some examples where the problem solved by this algorithm couldn't be solved in less than n
steps (again ignoring multiplicative and additive constants). The number of steps is at most n
and at least n
so this problem complexity is "exactly n
". Instead of saying "ignoring constant multiplicative/additive factor" every time we just write T(n)
for short.
Alternatives include arrays, generators, and inversion of control, but none is appropriate here.
Some (e.g. Microsoft in historical Win32) tend to use reference parameters for simplicity, because it's clear who allocates and how it will look on the stack, reduces the proliferation of structures, and allows a separate return value for success.
"Pure" programmers prefer the struct, assuming it is the function value (as is the case here), rather than something that's touched incidentally by the function. If you had a more complicated procedure, or something with state, you'd probably use references (assuming you have a reason for not using a class).
In Matlab, you can iterate over the elements in the list directly. This can be useful if you don't need to know which element you're currently working on.
Thus you can write
for elm = list
%# do something with the element
end
Note that Matlab iterates through the columns of list
, so if list
is a nx1 vector, you may want to transpose it.
The method mentioned by steenslag is terse, and given the scope of the question it should be considered the correct answer. However it is also worth knowing that this can be achieved with a regular expression, which if you aren't already familiar with in Ruby, is an important skill to learn.
Have a play with Rubular: http://rubular.com/
But in this case, the following ruby statement will return true if the string on the left starts with 'abc'. The \A in the regex literal on the right means 'the beginning of the string'. Have a play with rubular - it will become clear how things work.
'abcdefg' =~ /\Aabc/
Updated names for Swift 3.0
Based on Abhishek's answer and Druva's answer
func loadJson(forFilename fileName: String) -> NSDictionary? {
if let url = Bundle.main.url(forResource: fileName, withExtension: "json") {
if let data = NSData(contentsOf: url) {
do {
let dictionary = try JSONSerialization.jsonObject(with: data as Data, options: .allowFragments) as? NSDictionary
return dictionary
} catch {
print("Error!! Unable to parse \(fileName).json")
}
}
print("Error!! Unable to load \(fileName).json")
}
return nil
}
Just as another option if you want to print only the key (doesn't write the .env file) you can use:
php artisan key:generate --show
First up, going by the function name xssRequest it sounds like you're trying cross site request - which if that's right, you're not going to be able to read the contents of the iframe.
On the other hand, if the iframe's URL is on your domain you can access the body, but I've found that if I use a timeout to remove the iframe the callback works fine:
// possibly excessive use of jQuery - but I've got a live working example in production
$('#myUniqueID').load(function () {
if (typeof callback == 'function') {
callback($('body', this.contentWindow.document).html());
}
setTimeout(function () {$('#frameId').remove();}, 50);
});
If you're using Gradle, rebuild Gradle can solve this problem.
Use the shell function test
:
foo:
test $(something)
Usage:
$ make foo
test
Makefile:2: recipe for target 'foo' failed
make: *** [foo] Error 1
$ make foo something=x
test x
To show both string.Split
and Regex
usage:
string input = "abc][rfd][5][,][.";
string[] parts1 = input.Split(new string[] { "][" }, StringSplitOptions.None);
string[] parts2 = Regex.Split(input, @"\]\[");
You have to open that file with a text editor and then save it.
touch ~/.bash_profile; open ~/.bash_profile
It will open the file with TextEdit, paste your things and then save it. If you open it again you'll find your edits.
You can use other editors:
nano ~/.bash_profile
mate ~/.bash_profile
vim ~/.bash_profile
But if you don't know how to use them, it's easier to use the open
approach.
Alternatively, you can rely on pbpaste
. Copy
export ANDROID_HOME=/<installation location>/android-sdk-macosx
export PATH=${PATH}:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools
in the system clipboard and then in a shell run
pbpaste > ~/.bash_profile
Or alternatively you can also use cat
cat > ~/.bash_profile
(now cat
waits for input: paste the two export definitions and then hit ctrl-D).
(x > 0 for x in list)
in that function call creates a generator expression eg.
>>> nums = [1, 2, -1, 9, -5]
>>> genexp = (x > 0 for x in nums)
>>> for x in genexp:
print x
True
True
False
True
False
Which any
uses, and shortcircuits on encountering the first object that evaluates True
There are some working solutions here already, but here's another one:
>>> import types
>>> class Dummy: pass
>>> type(Dummy) is types.ClassType
True
This may be an answer (for spring boot 2) and a question at the same time. It seems that in spring boot 2 combined with spring security everything (means every route/antmatcher) is protected by default if you use an individual security mechanism extended from
WebSecurityConfigurerAdapter
If you don´t use an individual security mechanism, everything is as it was?
In older spring boot versions (1.5 and below) as Andy Wilkinson states in his above answer places like public/** or static/**
are permitted by default.
So to sum this question/answer up - if you are using spring boot 2 with spring security and have an individual security mechanism you have to exclusivley permit access to static contents placed on any route. Like so:
@Configuration
public class SpringSecurityConfiguration extends WebSecurityConfigurerAdapter {
private final ThdAuthenticationProvider thdAuthenticationProvider;
private final ThdAuthenticationDetails thdAuthenticationDetails;
/**
* Overloaded constructor.
* Builds up the needed dependencies.
*
* @param thdAuthenticationProvider a given authentication provider
* @param thdAuthenticationDetails given authentication details
*/
@Autowired
public SpringSecurityConfiguration(@NonNull ThdAuthenticationProvider thdAuthenticationProvider,
@NonNull ThdAuthenticationDetails thdAuthenticationDetails) {
this.thdAuthenticationProvider = thdAuthenticationProvider;
this.thdAuthenticationDetails = thdAuthenticationDetails;
}
/**
* Creates the AuthenticationManager with the given values.
*
* @param auth the AuthenticationManagerBuilder
*/
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) {
auth.authenticationProvider(thdAuthenticationProvider);
}
/**
* Configures the http Security.
*
* @param http HttpSecurity
* @throws Exception a given exception
*/
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.requestMatchers(PathRequest.toStaticResources().atCommonLocations()).permitAll()
.antMatchers("/management/**").hasAnyAuthority(Role.Role_Engineer.getValue(),
Role.Role_Admin.getValue())
.antMatchers("/settings/**").hasAnyAuthority(Role.Role_Engineer.getValue(),
Role.Role_Admin.getValue())
.anyRequest()
.fullyAuthenticated()
.and()
.formLogin()
.authenticationDetailsSource(thdAuthenticationDetails)
.loginPage("/login").permitAll()
.defaultSuccessUrl("/bundle/index", true)
.failureUrl("/denied")
.and()
.logout()
.invalidateHttpSession(true)
.logoutSuccessUrl("/login")
.logoutUrl("/logout")
.and()
.exceptionHandling()
.accessDeniedHandler(new CustomAccessDeniedHandler());
}
}
Please mind this line of code, which is new:
.requestMatchers(PathRequest.toStaticResources().atCommonLocations()).permitAll()
If you use spring boot 1.5 and below you don´t need to permit these locations (static/public/webjars etc.) explicitly.
Here is the official note, what has changed in the new security framework as to old versions of itself:
Security changes in Spring Boot 2.0 M4
I hope this helps someone. Thank you! Have a nice day!
You can use &
in place of &
Whenever you have seen coding from open source community like Guava and from Google Developer (Android Library) they used this approach
List<String> strings = new ArrayList<String>();
because it's hide the implementation detail from user. You precisely
List<String> strings = new ArrayList<String>();
it's generic approach and this specialized approach
ArrayList<String> strings = new ArrayList<String>();
For Reference: Effective Java 2nd Edition: Item 52: Refer to objects by their interfaces
If you are trying to separate strings into multiple lines, you can use the "+". For example:
$header = "Make," +
"ComputerName," +
"Model," +
"Windows Version"
Will look just like:
$header = "Make,ComputerName,Model,Windows Version"
After INSERT
query you can use ROW_COUNT()
to check for successful insert operation as:
SELECT IF(ROW_COUNT() = 1, "Insert Success", "Insert Failed") As status;
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
window.location.href = marker.url;
}
})(marker, i));
If you use numpy.multiply
S = [22, 33, 45.6, 21.6, 51.8]
P = 2.45
multiply(S, P)
It gives you as a result
array([53.9 , 80.85, 111.72, 52.92, 126.91])
printf
allows formatting with width specifiers. For example,
printf( "%-30s %s\n", "Starting initialization...", "Ok." );
You would use a negative width specifier to indicate left-justification because the default is to use right-justification.
Using the suggested Maven properties plugin I was able to read in a buildNumber.properties file that I use to version my builds.
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>properties-maven-plugin</artifactId>
<version>1.0-alpha-1</version>
<executions>
<execution>
<phase>initialize</phase>
<goals>
<goal>read-project-properties</goal>
</goals>
<configuration>
<files>
<file>${basedir}/../project-parent/buildNumber.properties</file>
</files>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
In Designer, activate the centralWidget and assign a layout, e.g. horizontal or vertical layout. Then your QFormLayout will automatically resize.
Always make sure, that all widgets have a layout! Otherwise, automatic resizing will break with that widget!
Controls insist on being too large, and won't resize, in QtDesigner
I had this same problem.
Did:
f1 = plt.figure(1)
# code for figure 1
# don't write 'plt.show()' here
f2 = plt.figure(2)
# code for figure 2
plt.show()
Write 'plt.show()' only once, after the last figure.
Worked for me.
Hello...I have created a java client server application in swing for caesar cipher...I have created a new formula that can decrypt the text properly... sorry only for lower case..!
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.net.*;
import java.util.*;
public class ceasarserver extends JFrame implements ActionListener {
static String cs = "abcdefghijklmnopqrstuvwxyz";
static JLabel l1, l2, l3, l5, l6;
JTextField t1;
JButton close, b1;
static String en;
int num = 0;
JProgressBar progress;
ceasarserver() {
super("SERVER");
JPanel p = new JPanel(new GridLayout(10, 1));
l1 = new JLabel("");
l2 = new JLabel("");
l3 = new JLabel("");
l5 = new JLabel("");
l6 = new JLabel("Enter the Key...");
t1 = new JTextField(30);
progress = new JProgressBar(0, 20);
progress.setValue(0);
progress.setStringPainted(true);
close = new JButton("Close");
close.setMnemonic('C');
close.setPreferredSize(new Dimension(300, 25));
close.addActionListener(this);
b1 = new JButton("Decrypt");
b1.setMnemonic('D');
b1.addActionListener(this);
p.add(l1);
p.add(l2);
p.add(l3);
p.add(l6);
p.add(t1);
p.add(b1);
p.add(progress);
p.add(l5);
p.add(close);
add(p);
setVisible(true);
pack();
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == close)
System.exit(0);
else if (e.getSource() == b1) {
int key = Integer.parseInt(t1.getText());
String d = "";
int i = 0, j, k;
while (i < en.length()) {
j = cs.indexOf(en.charAt(i));
k = (j + (26 - key)) % 26;
d = d + cs.charAt(k);
i++;
}
while (num < 21) {
progress.setValue(num);
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
}
progress.setValue(num);
Rectangle progressRect = progress.getBounds();
progressRect.x = 0;
progressRect.y = 0;
progress.paintImmediately(progressRect);
num++;
}
l5.setText("Decrypted text: " + d);
}
}
public static void main(String args[]) throws IOException {
new ceasarserver();
String strm = new String();
ServerSocket ss = new ServerSocket(4321);
l1.setText("Secure data transfer Server Started....");
Socket s = ss.accept();
l2.setText("Client Connected !");
while (true) {
Scanner br1 = new Scanner(s.getInputStream());
en = br1.nextLine();
l3.setText("Client:" + en);
}
}
The client class:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.net.*;
import java.util.*;
public class ceasarclient extends JFrame {
String cs = "abcdefghijklmnopqrstuvwxyz";
static JLabel l1, l2, l3, l4, l5;
JButton b1, b2, b3;
JTextField t1, t2;
JProgressBar progress;
int num = 0;
String en = "";
ceasarclient(final Socket s) {
super("CLIENT");
JPanel p = new JPanel(new GridLayout(10, 1));
setSize(500, 500);
t1 = new JTextField(30);
b1 = new JButton("Send");
b1.setMnemonic('S');
b2 = new JButton("Close");
b2.setMnemonic('C');
l1 = new JLabel("Welcome to Secure Data transfer!");
l2 = new JLabel("Enter the word here...");
l3 = new JLabel("");
l4 = new JLabel("Enter the Key:");
b3 = new JButton("Encrypt");
b3.setMnemonic('E');
t2 = new JTextField(30);
progress = new JProgressBar(0, 20);
progress.setValue(0);
progress.setStringPainted(true);
p.add(l1);
p.add(l2);
p.add(t1);
p.add(l4);
p.add(t2);
p.add(b3);
p.add(progress);
p.add(b1);
p.add(l3);
p.add(b2);
add(p);
setVisible(true);
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
PrintWriter pw = new PrintWriter(s.getOutputStream(), true);
pw.println(en);
} catch (Exception ex) {
}
;
l3.setText("Encrypted Text Sent.");
}
});
b3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String strw = t1.getText();
int key = Integer.parseInt(t2.getText());
int i = 0, j, k;
while (i < strw.length()) {
j = cs.indexOf(strw.charAt(i));
k = (j + key) % 26;
en = en + cs.charAt(k);
i++;
}
while (num < 21) {
progress.setValue(num);
try {
Thread.sleep(100);
} catch (InterruptedException exe) {
}
progress.setValue(num);
Rectangle progressRect = progress.getBounds();
progressRect.x = 0;
progressRect.y = 0;
progress.paintImmediately(progressRect);
num++;
}
}
});
b2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
pack();
}
public static void main(String args[]) throws IOException {
final Socket s = new Socket(InetAddress.getLocalHost(), 4321);
new ceasarclient(s);
}
}
A workspace is a collection of projects. It's useful to organize your projects when there's correlation between them (e.g.: Project A includes a library, that is provided as a project itself as project B. When you build the workspace project B is compiled and linked in project A).
It's common to use a workspace in the popular CocoaPods. When you install your pods, they are placed inside a workspace, that holds your project and the pod libraries.
A little late, but a useful plugin that will actually use a mask to give a bit more restriction on user input.
<div class="col-sm-3 col-md-6 col-lg-4">
<div class="form-group">
<label for="addPhone">Phone Number *</label>
<input id="addPhone" name="addPhone" type="text" class="form-control
required" data-mask="(999) 999-9999"placeholder>
<span class="help-block">(999) 999-9999</span>
</div>
</div>
<!-- Input Mask -->
<script src="js/plugins/jasny/jasny-bootstrap.min.js"></script>
More info on the plugin https://www.jasny.net/bootstrap/2.3.1/javascript.html#inputmask
An Object file is the compiled file itself. There is no difference between the two.
An executable file is formed by linking the Object files.
Object file contains low level instructions which can be understood by the CPU. That is why it is also called machine code.
This low level machine code is the binary representation of the instructions which you can also write directly using assembly language and then process the assembly language code (represented in English) into machine language (represented in Hex) using an assembler.
Here's a typical high level flow for this process for code in High Level Language such as C
--> goes through pre-processor
--> to give optimized code, still in C
--> goes through compiler
--> to give assembly code
--> goes through an assembler
--> to give code in machine language which is stored in OBJECT FILES
--> goes through Linker
--> to get an executable file.
This flow can have some variations for example most compilers can directly generate the machine language code, without going through an assembler. Similarly, they can do the pre-processing for you. Still, it is nice to break up the constituents for a better understanding.
In pymongo you can update with:
mycollection.update({'_id':mongo_id}, {"$set": post}, upsert=False)
Upsert parameter will insert instead of updating if the post is not found in the database.
Documentation is available at mongodb site.
UPDATE For version > 3 use update_one instead of update:
mycollection.update_one({'_id':mongo_id}, {"$set": post}, upsert=False)
if you are on Windows
sqlplus / as sysdba
Now you are logged with SYS user and you can do anything you want (query DBA_USERS to find out your username, or change any user password). You can not see the old password, you can only change it.
Something has deleted your ibdata1 file where InnoDB keeps the dictionary. Definitely it's not MySQL who does it.
UPDATE: I made a tutorial on how to fix the error - https://youtu.be/014KbCYayuE
Fix: Unlock your device before running it.
Hi Guys: Think I may have a fix for this:
Sounds ridiculous but try unlocking your Virtual Device; i.e. use your mouse to swipe and open. Your app should then work!!
Try this:
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
public class WriteImage
{
public static void main( String[] args )
{
BufferedImage image = null;
try {
URL url = new URL("URL_IMAGE");
image = ImageIO.read(url);
ImageIO.write(image, "jpg",new File("C:\\out.jpg"));
ImageIO.write(image, "gif",new File("C:\\out.gif"));
ImageIO.write(image, "png",new File("C:\\out.png"));
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Done");
}
}
You can do it like this:
angular.element('#modal').modal('hide');
Insert Selected column with condition
INSERT INTO where_to_insert (col_1,col_2) SELECT col1, col2 FROM from_table WHERE condition;
Copy all data from one table to another with the same column name.
INSERT INTO where_to_insert
SELECT * FROM from_table WHERE condition;
What about something like this?
<?php
$URL = "http://example.com";
$base = '<base href="'.$URL.'">';
$host = preg_replace('/^[^\/]+\/\//', '', $URL);
$tarray = explode('/', $host);
$host = array_shift($tarray);
$URI = '/' . implode('/', $tarray);
$content = '';
$fp = @fsockopen($host, 80, $errno, $errstr, 30);
if(!$fp) { echo "Unable to open socked: $errstr ($errno)\n"; exit; }
fwrite($fp,"GET $URI HTTP/1.0\r\n");
fwrite($fp,"Host: $host\r\n");
if( isset($_SERVER["HTTP_USER_AGENT"]) ) { fwrite($fp,'User-Agent: '.$_SERVER
["HTTP_USER_AGENT"]."\r\n"); }
fwrite($fp,"Connection: Close\r\n");
fwrite($fp,"\r\n");
while (!feof($fp)) { $content .= fgets($fp, 128); }
fclose($fp);
if( strpos($content,"\r\n") > 0 ) { $eolchar = "\r\n"; }
else { $eolchar = "\n"; }
$eolpos = strpos($content,"$eolchar$eolchar");
$content = substr($content,($eolpos + strlen("$eolchar$eolchar")));
if( preg_match('/<head\s*>/i',$content) ) { echo( preg_replace('/<head\s*>/i','<head>'.
$base,$content,1) ); }
else { echo( preg_replace('/<([a-z])([^>]+)>/i',"<\\1\\2>".$base,$content,1) ); }
?>
NUMERIC(3,2)
means: 3 digits in total, 2 after the decimal point. So you only have a single decimal before the decimal point.
Try NUMERIC(5,2)
- three before, two after the decimal point.
Donno how or why but i manage to find this around and it works for me, i had the problem I wanted to return the result of executing a bash
$ while true; do { echo -e 'HTTP/1.1 200 OK\r\n'; sh test; } | nc -l 8080; done
NOTE: This command was taken from: http://www.razvantudorica.com/08/web-server-in-one-line-of-bash
this executes bash script test and return the result to a browser client connecting to the server running this command on port 8080
My script does this ATM
$ nano test
#!/bin/bash
echo "************PRINT SOME TEXT***************\n"
echo "Hello World!!!"
echo "\n"
echo "Resources:"
vmstat -S M
echo "\n"
echo "Addresses:"
echo "$(ifconfig)"
echo "\n"
echo "$(gpio readall)"
and my web browser is showing
************PRINT SOME TEXT***************
Hello World!!!
Resources:
procs -----------memory---------- ---swap-- -----io---- -system-- ----cpu----
r b swpd free buff cache si so bi bo in cs us sy id wa
0 0 0 314 18 78 0 0 2 1 306 31 0 0 100 0
Addresses:
eth0 Link encap:Ethernet HWaddr b8:27:eb:86:e8:c5
inet addr:192.168.1.83 Bcast:192.168.1.255 Mask:255.255.255.0
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:27734 errors:0 dropped:0 overruns:0 frame:0
TX packets:26393 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:1924720 (1.8 MiB) TX bytes:3841998 (3.6 MiB)
lo Link encap:Local Loopback
inet addr:127.0.0.1 Mask:255.0.0.0
UP LOOPBACK RUNNING MTU:65536 Metric:1
RX packets:0 errors:0 dropped:0 overruns:0 frame:0
TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:0 (0.0 B) TX bytes:0 (0.0 B)
GPIOs:
+----------+-Rev2-+------+--------+------+-------+
| wiringPi | GPIO | Phys | Name | Mode | Value |
+----------+------+------+--------+------+-------+
| 0 | 17 | 11 | GPIO 0 | IN | Low |
| 1 | 18 | 12 | GPIO 1 | IN | Low |
| 2 | 27 | 13 | GPIO 2 | IN | Low |
| 3 | 22 | 15 | GPIO 3 | IN | Low |
| 4 | 23 | 16 | GPIO 4 | IN | Low |
| 5 | 24 | 18 | GPIO 5 | IN | Low |
| 6 | 25 | 22 | GPIO 6 | IN | Low |
| 7 | 4 | 7 | GPIO 7 | IN | Low |
| 8 | 2 | 3 | SDA | IN | High |
| 9 | 3 | 5 | SCL | IN | High |
| 10 | 8 | 24 | CE0 | IN | Low |
| 11 | 7 | 26 | CE1 | IN | Low |
| 12 | 10 | 19 | MOSI | IN | Low |
| 13 | 9 | 21 | MISO | IN | Low |
| 14 | 11 | 23 | SCLK | IN | Low |
| 15 | 14 | 8 | TxD | ALT0 | High |
| 16 | 15 | 10 | RxD | ALT0 | High |
| 17 | 28 | 3 | GPIO 8 | ALT2 | Low |
| 18 | 29 | 4 | GPIO 9 | ALT2 | Low |
| 19 | 30 | 5 | GPIO10 | ALT2 | Low |
| 20 | 31 | 6 | GPIO11 | ALT2 | Low |
+----------+------+------+--------+------+-------+
simply amazing!
How about something like this...
Dim rs As RecordSet
Set rs = Currentdb.OpenRecordSet("SELECT PictureLocation, ID FROM MyAccessTable;")
Do While Not rs.EOF
Debug.Print rs("PictureLocation") & " - " & rs("ID")
rs.MoveNext
Loop
When you mean user presses, do you mean a click? A click is when the user presses down and then immediately lifts up finger. Therefore it is encompassing two onTouch Events. You should save the use of onTouchEvent for stuff that happens on the initial touch or the after release.
Thus, you should be using onClickListener if it is a click.
Your answer is analogous: Use onLongClickListener.
select GROUP_CONCAT(stat SEPARATOR ' ') from (select concat('KILL ',id,';') as stat from information_schema.processlist) as stats;
Then copy and paste the result back into the terminal. Something like:
KILL 2871; KILL 2879; KILL 2874; KILL 2872; KILL 2866;
hi frind code type in terminal swift -v
print teminal Welcome to Apple Swift version 5.2.4 (swiftlang-1103.0.32.9 clang-1103.0.32.53).
as header
AUTH=$(echo -ne "$BASIC_AUTH_USER:$BASIC_AUTH_PASSWORD" | base64 --wrap 0)
curl \
--header "Content-Type: application/json" \
--header "Authorization: Basic $AUTH" \
--request POST \
--data '{"key1":"value1", "key2":"value2"}' \
https://example.com/
html
<ul class="answerList" id="oneAnswer">
<li class="answer" value="false">info1</li>
<li class="answer" value="false">info2</li>
<li class="answer" value="false">info3</li>
</ul>
Get index,text,value js
$('#oneAnswer li').each(function (i) {
var index = $(this).index();
var text = $(this).text();
var value = $(this).attr('value');
alert('Index is: ' + index + ' and text is ' + text + ' and Value ' + value);
});
For Ubuntu 12.04.3 LTS (Precise Pangolin) I had to do:
apt-get install libxml2-dev libxslt1-dev
(Note the "1" in libxslt1-dev)
Then I just installed lxml with pip/easy_install.
Be aware of the "date=iso
" format: it isn't exactly ISO 8601.
See commit "466fb67" from Beat Bolli (bbolli
), for Git 2.2.0 (November 2014)
Git's "ISO" date format does not really conform to the ISO 8601 standard due to small differences, and it cannot be parsed by ISO 8601-only parsers, e.g. those of XML toolchains.
The output from "
--date=iso
" deviates from ISO 8601 in these ways:
- a space instead of the
T
date/time delimiter- a space between time and time zone
- no colon between hours and minutes of the time zone
Add a strict ISO 8601 date format for displaying committer and author dates.
Use the '%aI
' and '%cI
' format specifiers and add '--date=iso-strict
' or '--date=iso8601-strict
' date format names.
See this thread for discussion.
Try this to get value from select element by Element Name
$("select[name=elementnamehere]").val();
I don't know if this exists in Visual Studio 2008 but in Visual Studio 2010+ you can easily do this by:
Don't select anything, then press Ctrl + C And then (without doing anything else) Ctrl + V
This is iteration using block approach:
NSDictionary *dict = @{@"key1":@1, @"key2":@2, @"key3":@3};
[dict enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
NSLog(@"%@->%@",key,obj);
// Set stop to YES when you wanted to break the iteration.
}];
With autocompletion is very fast to set, and you do not have to worry about writing iteration envelope.
This method works best to me:
Element.prototype.remove = function() {
this.parentElement.removeChild(this);
}
NodeList.prototype.remove = HTMLCollection.prototype.remove = function() {
for(var i = this.length - 1; i >= 0; i--) {
if(this[i] && this[i].parentElement) {
this[i].parentElement.removeChild(this[i]);
}
}
}
To use it we can deploy like this:
document.getElementsByID('DIV_Id').remove();
or
document.getElementsByClassName('DIV_Class').remove();
I want to point to the way Wordpress handles this:
define( 'ABSPATH', dirname( __FILE__ ) . '/' );
As Wordpress is very heavy used all over the web and also works fine locally I have much trust in this method. You can find this definition on the bottom of your wordpress wp-config.php
file
There is indeed a fancy shmancy native function in java you should leverage.
ArrayList has an instance method called
indexOf(Object o)
(http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html)
You would be able to call it on _categories
as follows:
_categories.indexOf("camels")
I have no experience with programming for Android - but this would work for a standard Java application.
Good luck.
For the best effect you have to use a custom (stretchable) background image. This is also how the UITextField
's rounded border is drawn.
Not sure if this answer the question or going to help....
$dt = '6/26/1970' ; // or // '6.26.1970' ;
$dt = preg_replace("([.]+)", "/", $dt);
$test_arr = explode('/', $dt);
if (checkdate($test_arr[0], $test_arr[1], $test_arr[2]) && preg_match("/[0-9]{1,2}\/[0-9]{1,2}\/[0-9]{4}/", $dt))
{ echo(date('Y-m-d', strtotime("$dt")) . "<br>"); }
else
{ echo "no good...format must be in mm/dd/yyyy"; }
Actually there is a more simple solution (only on Mac version). Just four steps:
Yes, assignment is supported for structs. However, there are problems:
struct S {
char * p;
};
struct S s1, s2;
s1.p = malloc(100);
s2 = s1;
Now the pointers of both structs point to the same block of memory - the compiler does not copy the pointed to data. It is now difficult to know which struct instance owns the data. This is why C++ invented the concept of user-definable assignment operators - you can write specific code to handle this case.
An implicit interface implementation is where you have a method with the same signature of the interface.
An explicit interface implementation is where you explicitly declare which interface the method belongs to.
interface I1
{
void implicitExample();
}
interface I2
{
void explicitExample();
}
class C : I1, I2
{
void implicitExample()
{
Console.WriteLine("I1.implicitExample()");
}
void I2.explicitExample()
{
Console.WriteLine("I2.explicitExample()");
}
}
I'm a beginner, but I had that problem while playing around with the "Hello Grid View". I was trying to use my own photos, which were all very large in file size.
The quick fix was to reduce the number of photos, thus reducing the size of the APK file.
But, I guess my follow up question for anybody else who hits this thread is this: How do I attach large files like JPGs and MP3s to an app and make sure they save on the SD Card so the APK remains small?
Yes. In Ruby the not equal to operator is:
!=
You can get a full list of ruby operators here: https://www.tutorialspoint.com/ruby/ruby_operators.htm.
I just created this and it looks easier. You get these 2 functions:
=GetColorIndex(E5) <- returns color number for the cell
from (cell)
=CountColorIndexInRange(C7:C24,14) <- returns count of cells C7:C24 with color 14
from (range of cells, color number you want to count)
example shows percent of cells with color 14
=ROUND(CountColorIndexInRange(C7:C24,14)/18, 4 )
Create these 2 VBA functions in a Module (hit Alt-F11)
open + folders. double-click on Module1
Just paste this text below in, then close the module window (it must save it then):
Function GetColorIndex(Cell As Range)
GetColorIndex = Cell.Interior.ColorIndex
End Function
Function CountColorIndexInRange(Rng As Range, TestColor As Long)
Dim cnt
Dim cl As Range
cnt = 0
For Each cl In Rng
If GetColorIndex(cl) = TestColor Then
Rem Debug.Print ">" & TestColor & "<"
cnt = cnt + 1
End If
Next
CountColorIndexInRange = cnt
End Function
In your phone go to Settings->Connect
to PC.
There you will see the option Default Connection Type
. Select it and set it to your preference.
Selectors are an efficient way to reference methods directly in compiled code - the compiler is what actually assigns the value to a SEL.
Other have already covered the second part of your q, the ':' at the end matches a different signature than what you're looking for (in this case that signature doesn't exist).
Simplest of all solutions:
filtered_df = df[df['var2'].isnull()]
This filters and gives you rows which has only NaN
values in 'var2'
column.
I found that on Windows 8.1 with an instance of SQL 2014 already installed, if I ran the SQLEXPR.EXE and then dismissed the Windows 'warning this may be incompatible' dialogs, that the installer completed successfully.
I suspect having 2014 bits already in place probably helped.
import React, { Component } from "react";
import axios from "axios";
const CancelToken = axios.CancelToken;
let cancel;
class Abc extends Component {
componentDidMount() {
this.Api();
}
Api() {
// Cancel previous request
if (cancel !== undefined) {
cancel();
}
axios.post(URL, reqBody, {
cancelToken: new CancelToken(function executor(c) {
cancel = c;
}),
})
.then((response) => {
//responce Body
})
.catch((error) => {
if (axios.isCancel(error)) {
console.log("post Request canceled");
}
});
}
render() {
return <h2>cancel Axios Request</h2>;
}
}
export default Abc;
For anyone else out there wondering how to do this, I have the following solution for SQL Server 2008 R2 and later:
USE master
go
DENY VIEW ANY DATABASE TO [user]
go
This will address exactly the requirement outlined above..
UPDATE 2019: You can bypass X-Frame-Options
in an <iframe>
using just client-side JavaScript and my X-Frame-Bypass Web Component. Here is a demo: Hacker News in an X-Frame-Bypass
. (Tested in Chrome & Firefox.)
If you are using Resharper make sure it does not add the wrong header for you, very common cases with ReSharper are:
#include <consoleapi2.h
#include <apiquery2.h>
#include <fileapi.h>
UPDATE:
Another suggestion is to check if you are including a "partial Windows.h", what I mean is that if you include for example winbase.h or minwindef.h you may end up with that error, add "the big" Windows.h instead. There are also some less obvious cases that I went through, the most notable was when I only included synchapi.h, the docs clearly state that is the header to be included for some functions like AcquireSRWLockShared but it triggered the No target architecture, the fix was to remove the synchapi.h and include "the big" Windows.h.
The Windows.h is huge, it defines macros(many of them remove the No target arch error) and includes many other headers. In summary, always check if you are including some header that could be replaced by Windows.h because it is not unusual to include a header that relies on some constants that are defined by Windows.h, so if you fail to include this header your compilation may fail.
You Could always use and leave out the "when not matched section"
merge into table1 FromTable
using table2 ToTable
on ( FromTable.field1 = ToTable.field1
and FromTable.field2 =ToTable.field2)
when Matched then
update set
ToTable.fieldr = FromTable.fieldx,
ToTable.fields = FromTable.fieldy,
ToTable.fieldt = FromTable.fieldz)
when not matched then
insert (ToTable.field1,
ToTable.field2,
ToTable.fieldr,
ToTable.fields,
ToTable.fieldt)
values (FromTable.field1,
FromTable.field2,
FromTable.fieldx,
FromTable.fieldy,
FromTable.fieldz);
If you look at Twitter's own container-app.html demo on GitHub, you'll get some ideas on using borders with their grid.
For example, here's the extracted part of the building blocks to their 940-pixel wide 16-column grid system:
.row {
zoom: 1;
margin-left: -20px;
}
.row > [class*="span"] {
display: inline;
float: left;
margin-left: 20px;
}
.span4 {
width: 220px;
}
To allow for borders on specific elements, they added embedded CSS to the page that reduces matching classes by enough amount to account for the border(s).
For example, to allow for the left border on the sidebar, they added this CSS in the <head>
after the the main <link href="../bootstrap.css" rel="stylesheet">
.
.content .span4 {
margin-left: 0;
padding-left: 19px;
border-left: 1px solid #eee;
}
You'll see they've reduced padding-left
by 1px
to allow for the addition of the new left border. Since this rule appears later in the source order, it overrides any previous or external declarations.
I'd argue this isn't exactly the most robust or elegant approach, but it illustrates the most basic example.
Target-Action allows three different forms of action selector:
- (void)action
- (void)action:(id)sender
- (void)action:(id)sender forEvent:(UIEvent *)event
Extract the zip file into a folder, e.g. C:\Program Files\Java\
and it will create a jdk-11
folder (where the bin folder is a direct sub-folder). You may need Administrator privileges to extract the zip file to this location.
Set a PATH:
C:\WINDOWS\system32;C:\WINDOWS;"C:\Program Files\Java\jdk-11\bin"
Set JAVA_HOME:
bin
sub-folder).You are set.
To see if it worked, open up the Command Prompt and type java -version
and see if it prints your newly installed JDK.
If you want to uninstall - just undo the above steps.
Note: You can also point JAVA_HOME
to the folder of your JDK installations and then set the PATH
variable to %JAVA_HOME%\bin
. So when you want to change the JDK you change only the JAVA_HOME
variable and leave PATH
as it is.
You can also use some existing API's like GroupDocs.Viewer which can convert your document into image or html and then you will be able to display it in your own application.
Upgrade to PostgreSQL 9.5 or greater. If (not) exists was introduced in version 9.5.
Apache commons lang now supports this. Just make sure you have a recent enough version of Apache commons lang on your classpath. You'll need version 3.2+
Release Notes for version 3.2
LANG-797: Added escape/unescapeJson to StringEscapeUtils.
Installing CuDNN just involves placing the files in the CUDA directory. If you have specified the routes and the CuDNN option correctly while installing caffe it will be compiled with CuDNN.
You can check that using cmake
. Create a directory caffe/build
and run cmake ..
from there. If the configuration is correct you will see these lines:
-- Found cuDNN (include: /usr/local/cuda-7.0/include, library: /usr/local/cuda-7.0/lib64/libcudnn.so)
-- NVIDIA CUDA:
-- Target GPU(s) : Auto
-- GPU arch(s) : sm_30
-- cuDNN : Yes
If everything is correct just run the make
orders to install caffe from there.
This works
@interface RGBComponents : NSObject {
float components[8];
}
@property(readonly) float * components;
- (float *) components {
return components;
}
The simple one line solution is
datediff(dd,'2010-12-31 15:13:48.593','2010-12-31 00:00:00.000')=0
datediff(dd,'2010-12-31 15:13:48.593','2010-12-31 00:00:00.000')<=1
datediff(dd,'2010-12-31 15:13:48.593','2010-12-31 00:00:00.000')>=1
You can try various option with this other than "dd"
there is a simple procedure to do it go to controlpanel->system and security ->system->advanced system settings->advanced->environment variables
then add new path enter this in your variable path and values
You just need to override onCreateDialog
in an Activity.
//In an Activity
private String[] mFileList;
private File mPath = new File(Environment.getExternalStorageDirectory() + "//yourdir//");
private String mChosenFile;
private static final String FTYPE = ".txt";
private static final int DIALOG_LOAD_FILE = 1000;
private void loadFileList() {
try {
mPath.mkdirs();
}
catch(SecurityException e) {
Log.e(TAG, "unable to write on the sd card " + e.toString());
}
if(mPath.exists()) {
FilenameFilter filter = new FilenameFilter() {
@Override
public boolean accept(File dir, String filename) {
File sel = new File(dir, filename);
return filename.contains(FTYPE) || sel.isDirectory();
}
};
mFileList = mPath.list(filter);
}
else {
mFileList= new String[0];
}
}
protected Dialog onCreateDialog(int id) {
Dialog dialog = null;
AlertDialog.Builder builder = new Builder(this);
switch(id) {
case DIALOG_LOAD_FILE:
builder.setTitle("Choose your file");
if(mFileList == null) {
Log.e(TAG, "Showing file picker before loading the file list");
dialog = builder.create();
return dialog;
}
builder.setItems(mFileList, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
mChosenFile = mFileList[which];
//you can do stuff with the file here too
}
});
break;
}
dialog = builder.show();
return dialog;
}
Alternative syntax using the -Not
operator and depending on your preference for readability:
if( -Not (Test-Path -Path $TARGETDIR ) )
{
New-Item -ItemType directory -Path $TARGETDIR
}
two of the best options are
$(this).parent("div:first")
$(this).parent().closest('div')
and of course you can find the class attr by
$(this).parent("div:first").attr("class")
$(this).parent().closest('div').attr("class")
when there are two variables one instance variable and other local variable of the same name then we use this. to refer current executing object to avoid the conflict between the names.
The repository is not down, it looks like they've changed how they host files (I guess they have restored some old code):
Now you have to add the /package-name/ before the -
Eg:
http://registry.npmjs.org/-/npm-1.1.48.tgz
http://registry.npmjs.org/npm/-/npm-1.1.48.tgz
There are 3 ways to solve it:
Use a public proxy:
--registry http://165.225.128.50:8000
Host a local proxy:
https://github.com/hughsk/npm-quickfix
git clone https://github.com/hughsk/npm-quickfix.git cd npm-quickfix npm set registry http://localhost:8080/ node index.js
I'd personally go with number 3 and revert to npm set registry http://registry.npmjs.org/
as soon as this get resolved.
Stay tuned here for more info: https://github.com/isaacs/npm/issues/2694
If you want to validate individual form field, but don't want for UI to be triggered and display any validation errors, you may consider to use Validator.check() method which returns if given field passes validation or not.
Here is example
var validator = $("#form").data('validator');
if(validator.check('#element')){
/*field is valid*/
}else{
/*field is not valid (but no errors will be displayed)*/
}
The following code will write an image in proportional to the response, you can modify the code for your purpose:
public void WriteImage(string path, int width, int height)
{
Bitmap srcBmp = new Bitmap(path);
float ratio = srcBmp.Width / srcBmp.Height;
SizeF newSize = new SizeF(width, height * ratio);
Bitmap target = new Bitmap((int) newSize.Width,(int) newSize.Height);
HttpContext.Response.Clear();
HttpContext.Response.ContentType = "image/jpeg";
using (Graphics graphics = Graphics.FromImage(target))
{
graphics.CompositingQuality = CompositingQuality.HighSpeed;
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphics.CompositingMode = CompositingMode.SourceCopy;
graphics.DrawImage(srcBmp, 0, 0, newSize.Width, newSize.Height);
using (MemoryStream memoryStream = new MemoryStream())
{
target.Save(memoryStream, ImageFormat.Jpeg);
memoryStream.WriteTo(HttpContext.Response.OutputStream);
}
}
Response.End();
}
I was in the same situation as you, the half answers scattered throughout the Internet were quite annoying, since it seemed that many people had the same issue, but no one could be bothered to fully explain how they solved it.
The Sonar docs refer to a GitHub project with examples that are helpful. What I did to solve this was to apply the integration tests logic to regular unit tests (although proper unit tests should be submodule specific, this isn't always the case).
In the parent pom.xml, add these properties:
<properties>
<!-- Sonar -->
<sonar.java.coveragePlugin>jacoco</sonar.java.coveragePlugin>
<sonar.dynamicAnalysis>reuseReports</sonar.dynamicAnalysis>
<sonar.jacoco.reportPath>${project.basedir}/../target/jacoco.exec</sonar.jacoco.reportPath>
<sonar.language>java</sonar.language>
</properties>
This will make Sonar pick up unit testing reports for all submodules in the same place (a target folder in the parent project). It also tells Sonar to reuse reports ran manually instead of rolling its own. We just need to make jacoco-maven-plugin run for all submodules by placing this in the parent pom, inside build/plugins:
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.6.0.201210061924</version>
<configuration>
<destFile>${sonar.jacoco.reportPath}</destFile>
<append>true</append>
</configuration>
<executions>
<execution>
<id>agent</id>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
</executions>
</plugin>
destFile
places the report file in the place where Sonar will look for it and append
makes it append to the file rather than overwriting it. This will combine all JaCoCo reports for all submodules in the same file.
Sonar will look at that file for each submodule, since that's what we pointed him at above, giving us combined unit testing results for multi module files in Sonar.
You should not include commands.c in your header file. In general, you should not include .c files. Rather, commands.c should include commands.h. As defined here, the C preprocessor is inserting the contents of commands.c into commands.h where the include is. You end up with two definitions of f123 in commands.h.
commands.h
#ifndef COMMANDS_H_
#define COMMANDS_H_
void f123();
#endif
commands.c
#include "commands.h"
void f123()
{
/* code */
}
You need add parameter errors='coerce'
to function to_numeric
:
ID = pd.to_numeric(ID, errors='coerce')
If ID
is column:
df.ID = pd.to_numeric(df.ID, errors='coerce')
but non numeric are converted to NaN
, so all values are float
.
For int
need convert NaN
to some value e.g. 0
and then cast to int
:
df.ID = pd.to_numeric(df.ID, errors='coerce').fillna(0).astype(np.int64)
Sample:
df = pd.DataFrame({'ID':['4806105017087','4806105017087','CN414149']})
print (df)
ID
0 4806105017087
1 4806105017087
2 CN414149
print (pd.to_numeric(df.ID, errors='coerce'))
0 4.806105e+12
1 4.806105e+12
2 NaN
Name: ID, dtype: float64
df.ID = pd.to_numeric(df.ID, errors='coerce').fillna(0).astype(np.int64)
print (df)
ID
0 4806105017087
1 4806105017087
2 0
EDIT: If use pandas 0.25+ then is possible use integer_na
:
df.ID = pd.to_numeric(df.ID, errors='coerce').astype('Int64')
print (df)
ID
0 4806105017087
1 4806105017087
2 NaN
Mainly this problem occurs because your library files get deleted. The simple way to work your project as it was working previously is 1) Go to Project properties 2) Select java Build Path 3) Remove all library except jre. 4) Now add the same same jar file by clicking "Add external jars".
Update for mid 2016:
The things are changing so fast that if it's late 2017 this answer might not be up to date anymore!
Beginners can quickly get lost in choice of build tools and workflows, but what's most up to date in 2016 is not using Bower, Grunt or Gulp at all! With help of Webpack you can do everything directly in NPM!
Google "npm as build tool" result: https://medium.com/@dabit3/introduction-to-using-npm-as-a-build-tool-b41076f488b0#.c33e74tsa
Don't get me wrong people use other workflows and I still use GULP in my legacy project(but slowly moving out of it), but this is how it's done in the best companies and developers working in this workflow make a LOT of money!
Look at this template it's a very up-to-date setup consisting of a mixture of the best and the latest technologies: https://github.com/coryhouse/react-slingshot
Your questions:
When I want to add a package (and check in the dependency into git), where does it belong - into package.json or into bower.json
Everything belongs in package.json now
Dependencies required for build are in "devDependencies" i.e. npm install require-dir --save-dev
(--save-dev updates your package.json by adding an entry to devDependencies)
npm install lodash --save
(--save updates your package.json by adding an entry to dependencies)If that is the case, when should I ever install packages explicitly like that without adding them to the file that manages dependencies (apart from installing command line tools globally)?
Always. Just because of comfort. When you add a flag (--save-dev
or --save
) the file that manages deps (package.json) gets updated automatically. Don't waste time by editing dependencies in it manually. Shortcut for npm install --save-dev package-name
is npm i -D package-name
and shortcut for npm install --save package-name
is npm i -S package-name
Try with following:
public DataTable fillDataTable(string table)
{
string query = "SELECT * FROM dstut.dbo." +table;
SqlConnection sqlConn = new SqlConnection(conSTR);
sqlConn.Open();
SqlCommand cmd = new SqlCommand(query, sqlConn);
SqlDataAdapter da=new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
sqlConn.Close();
return dt;
}
Hope it is helpful.
Update I've tidied up the SwingLink
class further and added more features; an up-to-date copy of it can be found here: https://bitbucket.org/dimo414/jgrep/src/tip/src/grep/SwingLink.java
@McDowell's answer is great, but there's several things that could be improved upon. Notably text other than the hyperlink is clickable and it still looks like a button even though some of the styling has been changed/hidden. While accessibility is important, a coherent UI is as well.
So I put together a class extending JLabel based on McDowell's code. It's self-contained, handles errors properly, and feels more like a link:
public class SwingLink extends JLabel {
private static final long serialVersionUID = 8273875024682878518L;
private String text;
private URI uri;
public SwingLink(String text, URI uri){
super();
setup(text,uri);
}
public SwingLink(String text, String uri){
super();
setup(text,URI.create(uri));
}
public void setup(String t, URI u){
text = t;
uri = u;
setText(text);
setToolTipText(uri.toString());
addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
open(uri);
}
public void mouseEntered(MouseEvent e) {
setText(text,false);
}
public void mouseExited(MouseEvent e) {
setText(text,true);
}
});
}
@Override
public void setText(String text){
setText(text,true);
}
public void setText(String text, boolean ul){
String link = ul ? "<u>"+text+"</u>" : text;
super.setText("<html><span style=\"color: #000099;\">"+
link+"</span></html>");
this.text = text;
}
public String getRawText(){
return text;
}
private static void open(URI uri) {
if (Desktop.isDesktopSupported()) {
Desktop desktop = Desktop.getDesktop();
try {
desktop.browse(uri);
} catch (IOException e) {
JOptionPane.showMessageDialog(null,
"Failed to launch the link, your computer is likely misconfigured.",
"Cannot Launch Link",JOptionPane.WARNING_MESSAGE);
}
} else {
JOptionPane.showMessageDialog(null,
"Java is not able to launch links on your computer.",
"Cannot Launch Link", JOptionPane.WARNING_MESSAGE);
}
}
}
You could also, for instance, change the link color to purple after being clicked, if that seemed useful. It's all self contained, you simply call:
SwingLink link = new SwingLink("Java", "http://java.sun.com");
mainPanel.add(link);
You can use these following lines in your main urls.py
you can add the text in the quotes to be displayed
To replace the text Django admin use admin.site.site_header = ""
To replace the text Site Administration use admin.site.site_title = ""
To replace the site name you can use admin.site.index_title = ""
To replace the url of the view site button you can use admin.site.site_url = ""
this
on a C++ compilerThe C++ compiler will silently lookup for a symbol if it does not find it immediately. Sometimes, most of the time, it is good:
But sometimes, You just don't want the compiler to guess. You want the compiler to pick-up the right symbol and not another.
For me, those times are when, within a method, I want to access to a member method or member variable. I just don't want some random symbol picked up just because I wrote printf
instead of print
. this->printf
would not have compiled.
The point is that, with C legacy libraries (§), legacy code written years ago (§§), or whatever could happen in a language where copy/pasting is an obsolete but still active feature, sometimes, telling the compiler to not play wits is a great idea.
These are the reasons I use this
.
(§) it's still a kind of mystery to me, but I now wonder if the fact you include the <windows.h> header in your source, is the reason all the legacy C libraries symbols will pollute your global namespace
(§§) realizing that "you need to include a header, but that including this header will break your code because it uses some dumb macro with a generic name" is one of those russian roulette moments of a coder's life
The pointsize command scales the size of points, but does not affect the size of dots.
In other words, plot ... with points ps 2
will generate points of twice the normal size, but for plot ... with dots ps 2
the "ps 2
" part is ignored.
You could use circular points (pt 7
), which look just like dots.
This is a very simple adaptation of the modifyList function by Sarkar. Because it is recursive, it will handle more complex situations than mapply
would, and it will handle mismatched name situations by ignoring the items in 'second' that are not in 'first'.
appendList <- function (x, val)
{
stopifnot(is.list(x), is.list(val))
xnames <- names(x)
for (v in names(val)) {
x[[v]] <- if (v %in% xnames && is.list(x[[v]]) && is.list(val[[v]]))
appendList(x[[v]], val[[v]])
else c(x[[v]], val[[v]])
}
x
}
> appendList(first,second)
$a
[1] 1 2
$b
[1] 2 3
$c
[1] 3 4
Alternatively you can register a call back delegate which ignores the certification error:
...
ServicePointManager.ServerCertificateValidationCallback = MyCertHandler;
...
static bool MyCertHandler(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors error)
{
// Ignore errors
return true;
}
For smaller arrays <10000 elements:
using System.Linq;
int firstArray = {5,4,2};
int secondArray = {3,2,1};
int[] result = firstArray.ToList().Concat(secondArray.ToList()).toArray();
[6] was spot on. I had the same problem ie a blank screen where wp-admin should have been Renaming plugins to pluginss let me get back in.
I also had a blank screen for my blog. The solution was to copy up a backup copy of wp-config,php somehow the 'live' wp-config.php had been replaced with a file size of zero.
It seems that it is very important to have an off-line backup The easy way to copy of the files is Filezilla (freeware)
You need a wordpress plugin for database backup - ie to back up all your pages and posts. But the pros will tell you that you need to get a
Peter
grep -F -r '0.49' *
treats 0.49 as a "fixed" string instead of a regular expression. This makes .
lose its special meaning.
I'm running Ubuntu, and as said above nobody:nobody does not work on Ubuntu. You get the error:
chown: invalid group: 'nobody:nobody'
Instead you should use the 'nogroup', like:
chown nobody:nogroup <dirname>
For completeness, write_csv()
from the readr
package is faster and never writes row names
# install.packages('readr', dependencies = TRUE)
library(readr)
write_csv(t, "t.csv")
If you need to write big data out, use fwrite()
from the data.table
package. It's much faster than both write.csv
and write_csv
# install.packages('data.table')
library(data.table)
fwrite(t, "t.csv")
Below is a benchmark that Edouard published on his site
microbenchmark(write.csv(data, "baseR_file.csv", row.names = F),
write_csv(data, "readr_file.csv"),
fwrite(data, "datatable_file.csv"),
times = 10, unit = "s")
## Unit: seconds
## expr min lq mean median uq max neval
## write.csv(data, "baseR_file.csv", row.names = F) 13.8066424 13.8248250 13.9118324 13.8776993 13.9269675 14.3241311 10
## write_csv(data, "readr_file.csv") 3.6742610 3.7999409 3.8572456 3.8690681 3.8991995 4.0637453 10
## fwrite(data, "datatable_file.csv") 0.3976728 0.4014872 0.4097876 0.4061506 0.4159007 0.4355469 10
I just got this error and i came to know that it is about the local variable alias
at the end of the stored procedure i had like
select @localvariable1,@localvariable2
it was working fine in sql but when i ran this in ssrs it was always throwing error but after I gave alias it is fixed
select @localvariable1 as A,@localvariable2 as B
According to MSDN, e.AddedItems
:
Gets a list that contains the items that were selected.
So you could use:
private void OnMyComboBoxChanged(object sender, SelectionChangedEventArgs e)
{
string text = (e.AddedItems[0] as ComboBoxItem).Content as string;
}
You could also use SelectedItem
if you use string
values for the Items
from the sender
:
private void OnMyComboBoxChanged(object sender, SelectionChangedEventArgs e)
{
string text = (sender as ComboBox).SelectedItem as string;
}
or
private void OnMyComboBoxChanged(object sender, SelectionChangedEventArgs e)
{
string text = ((sender as ComboBox).SelectedItem as ComboBoxItem).Content as string;
}
Since both Content
and SelectedItem
are objects, a safer approach would be to use .ToString()
instead of as string
Extracting into an Uber-dir works for me as we s should all be using root:\java and have outlets code in packages with versioning. Ie ca.tecreations-1.0.0. Signing is okay because the jars are intact from their downloaded location. 3rd party signatures intact, extract to c:\java. There’s my project dir. run from launcher so java -cp c:\java Launcher
Table A
+--------+-----------+
| A-num | text |
| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
+--------+-----------+
Table B
+------+------+--------------+
| B-num| date | A-num |
| 22 | 01.08.2003 | 2 |
| 23 | 02.08.2003 | 2 |
| 24 | 03.08.2003 | 1 |
| 25 | 04.08.2003 | 4 |
| 26 | 05.03.2003 | 4 |
I will update field text in table A with
UPDATE `Table A`,`Table B`
SET `Table A`.`text`=concat_ws('',`Table A`.`text`,`Table B`.`B-num`," from
",`Table B`.`date`,'/')
WHERE `Table A`.`A-num` = `Table B`.`A-num`
and come to this result:
Table A
+--------+------------------------+
| A-num | text |
| 1 | 24 from 03 08 2003 / |
| 2 | 22 from 01 08 2003 / |
| 3 | |
| 4 | 25 from 04 08 2003 / |
| 5 | |
--------+-------------------------+
where only one field from Table B is accepted, but I will come to this result:
Table A
+--------+--------------------------------------------+
| A-num | text |
| 1 | 24 from 03 08 2003 |
| 2 | 22 from 01 08 2003 / 23 from 02 08 2003 / |
| 3 | |
| 4 | 25 from 04 08 2003 / 26 from 05 03 2003 / |
| 5 | |
+--------+--------------------------------------------+
Had the same error but with a different scenario. I had my state as
this.state = {
date: new Date()
}
so when I was asking it in my Class Component I had
p>Date = {this.state.date}</p>
Instead of
p>Date = {this.state.date.toLocaleDateString()}</p>
If am not wrong
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
//You may decide to prompt to user
//else just kill
Process.GetCurrentProcess().Kill();
}
event.target
here is an HTMLElement
which is the parent of all HTML elements, but isn't guaranteed to have the property value
. TypeScript detects this and throws the error. Cast event.target
to the appropriate HTML element to ensure it is HTMLInputElement
which does have a value
property:
(<HTMLInputElement>event.target).value
Per the documentation:
Type the
$event
The example above casts the
$event
as anany
type. That simplifies the code at a cost. There is no type information that could reveal properties of the event object and prevent silly mistakes.[...]
The
$event
is now a specificKeyboardEvent
. Not all elements have avalue
property so it caststarget
to an input element.
(Emphasis mine)
I had the same problem on angular when switching page. I had to add this code before leaving the page to make it works:
$scope.$on('$locationChangeStart', function( event ) {
if(map != undefined)
{
map.remove();
map = undefined
document.getElementById('mapLayer').innerHTML = "";
}
});
Without document.getElementById('mapLayer').innerHTML = ""
the map was not displayed on the next page.
var newData = [1,2,3,4,5,6,7];
var chart = $('#chartjs').highcharts();
chart.series[0].setData(newData, true);
Explanation:
Variable newData
contains value that want to update in chart. Variable chart
is an object of a chart. setData
is a method provided by highchart to update data.
Method setData contains two parameters, in first parameter we need to pass new value as array and second param is Boolean value. If true
then chart updates itself and if false
then we have to use redraw()
method to update chart (i.e chart.redraw();
)
I tried re-creating this, and .someclass.notip
was being generated for me but .someclass:not(.notip)
was not, for as long as I did not have the @mixin tip()
defined. Once I had that, it all worked.
http://sassmeister.com/gist/9775949
$dropdown-width: 100px;
$comp-tip: true;
@mixin tip($pos:right) {
}
@mixin dropdown-pos($pos:right) {
&:not(.notip) {
@if $comp-tip == true{
@if $pos == right {
top:$dropdown-width * -0.6;
background-color: #f00;
@include tip($pos:$pos);
}
}
}
&.notip {
@if $pos == right {
top: 0;
left:$dropdown-width * 0.8;
background-color: #00f;
}
}
}
.someclass { @include dropdown-pos(); }
EDIT: http://sassmeister.com/ is a good place to debug your SASS because it gives you error messages. Undefined mixin 'tip'.
it what I get when I remove @mixin tip($pos:right) { }
r
opens for reading, whereas r+
opens for reading and writing. The b
is for binary.
This is spelled out in the documentation:
The most commonly-used values of mode are
'r'
for reading,'w'
for writing (truncating the file if it already exists), and'a'
for appending (which on some Unix systems means that all writes append to the end of the file regardless of the current seek position). If mode is omitted, it defaults to'r'
. The default is to use text mode, which may convert'\n'
characters to a platform-specific representation on writing and back on reading. Thus, when opening a binary file, you should append'b'
to the mode value to open the file in binary mode, which will improve portability. (Appending'b'
is useful even on systems that don’t treat binary and text files differently, where it serves as documentation.) See below for more possible values of mode.Modes
'r+'
,'w+'
and'a+'
open the file for updating (note that'w+'
truncates the file). Append'b'
to the mode to open the file in binary mode, on systems that differentiate between binary and text files; on systems that don’t have this distinction, adding the'b'
has no effect.
Edit your SVG file, add fill="currentColor"
to svg tag and make sure to remove any other fill property from the file.
For example:
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 139.435269383854" id="img" fill="currentColor">...
</svg>
Note that currentColor
is a keyword (not a fixed color in use).
After that, you can change the color using CSS, by setting the color
property of the element or from it's parent.
Example:
.div-with-svg-inside {
color: red;
}
I forgot to say, you must insert the SVG this way:
<svg>
<use xlink:href='/assets/file.svg#img'></use>
</svg>
Note that #img
is the id of the svg
tag inside svg file.
Another way of doing it: https://css-tricks.com/cascading-svg-fill-color/
Incase you're looping the OR conditions, you don't need the the second $query->where from the other posts (actually I don't think you need in general, you can just use orWhere in the nested where if easier)
$attributes = ['first'=>'a','second'=>'b'];
$query->where(function ($query) use ($attributes)
{
foreach ($attributes as $key=>value)
{
//you can use orWhere the first time, doesn't need to be ->where
$query->orWhere($key,$value);
}
});
you have to add the dependency for springs mvc
tray adding that in your pom
<!-- mvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>3.1.2.RELEASE</version>
</dependency>
In case you need to use it with Javascript
We can use arguments[0].click() to simulate click operation.
var element = element(by.linkText('webdriverjs'));
browser.executeScript("arguments[0].click()",element);
mysql version 5.5 set datetime default value as CURRENT_TIMESTAMP will be report error you can update to version 5.6 , it set datetime default value as CURRENT_TIMESTAMP
I've done this on a regular (local) TextView
, and it should work on the remote variety since the docs list the method as equivalent between the two:
remote_text_view.setText(Html.fromHtml("This is <del>crossed off</del>."));
curl's --data
will by default send Content-Type: application/x-www-form-urlencoded
in the request header. However, when using Postman's raw
body mode, Postman sends Content-Type: text/plain
in the request header.
So to achieve the same thing as Postman, specify -H "Content-Type: text/plain"
for curl:
curl -X POST -H "Content-Type: text/plain" --data "this is raw data" http://78.41.xx.xx:7778/
Note that if you want to watch the full request sent by Postman, you can enable debugging for packed app. Check this link for all instructions. Then you can inspect the app (right-click in Postman) and view all requests sent from Postman in the network
tab :
Always Use your selection as List
Eg:
var tempGroupOfFiles = Entities.Submited_Files.Where(r => r.FileStatusID == 10 && r.EventID == EventId).ToList();
Then Loop through the Collection while save changes
foreach (var item in tempGroupOfFiles)
{
var itemToUpdate = item;
if (itemToUpdate != null)
{
itemToUpdate.FileStatusID = 8;
itemToUpdate.LastModifiedDate = DateTime.Now;
}
Entities.SaveChanges();
}
I realise that it's been a very long time but thought I'd add anyway. If you just want the table, and not the create table statement you could use
select into x from db.schema.y where 1=0
to copy the table to a new DB
If you have Ruby for Windows,
C:\>more file
bath Abath Bbath XYZbathABC
C:\>ruby -pne "$_.gsub!(/bath/,\"hello\")" file
hello Ahello Bhello XYZhelloABC
I ended up going totally JS-free to avoid client-side render lag. To accomplish that, I generate HTML like this:
<span class="stars" title="{value as decimal}">
<span style="width={value/5*100}%;"/>
</span>
To help with accessibility, I even add the raw rating value in the title attribute.
They can be differentiated with where they are coming from or which developers they're targeting mainly.
Groovy is a bit like scripting version of Java. Long time Java programmers feel at home when building agile applications backed by big architectures. Groovy on Grails is, as the name suggests similar to the Rails framework. For people who don't want to bother with Java's verbosity all the time.
Scala is an object oriented and functional programming language and Ruby or Python programmers may feel more closer to this one. It employs quite a lot of common good ideas found in these programming languages.
Clojure is a dialect of the Lisp programming language so Lisp, Scheme or Haskell developers may feel at home while developing with this language.
If you are sure you want to remove all commit history, simply delete the .git
directory in your project root (note that it's hidden). Then initialize a new repository in the same folder and link it to the GitHub repository:
git init
git remote add origin [email protected]:user/repo
now commit your current version of code
git add *
git commit -am 'message'
and finally force the update to GitHub:
git push -f origin master
However, I suggest backing up the history (the .git
folder in the repository) before taking these steps!
Communicating between fragments is fairly complicated (I find the listeners concept a little challenging to implement).
It is common to use a 'Event Bus" to abstract these communications. This is a 3rd party library that takes care of this communication for you.
'Otto' is one that is used often to do this, and might be worth looking into: http://square.github.io/otto/
three condition may cause this issue.
gradle repeat contain,eg:
compile fileTree(include: [‘*.jar’], dir: ‘libs’)
compile files(‘libs/xxx.jar’)
if you can read chinese ,read hereError:Execution failed for task ':app:dexDebug'.> com.android.ide.common.process.ProcessException: o
Actualy you don't need an internet connection to use ip address. Each computer in LAN has an internal IP address you can discover by runing
ipconfig /all
in cmd.
You can use the ip address of the server (probabily something like 192.168.0.x or 10.0.0.x) to access the website remotely.
If you found the ip and still cannot access the website, it means WAMP is not configured to respond to that name ( what did you call me? 192.168.0.3? That's not my name. I'm Localhost ) and you have to modify ....../apache/config/httpd.conf
Listen *:80
Here is code for reading a matrix, note you also have a csvwrite function in matlab
void loadFromCSV( const std::string& filename )
{
std::ifstream file( filename.c_str() );
std::vector< std::vector<std::string> > matrix;
std::vector<std::string> row;
std::string line;
std::string cell;
while( file )
{
std::getline(file,line);
std::stringstream lineStream(line);
row.clear();
while( std::getline( lineStream, cell, ',' ) )
row.push_back( cell );
if( !row.empty() )
matrix.push_back( row );
}
for( int i=0; i<int(matrix.size()); i++ )
{
for( int j=0; j<int(matrix[i].size()); j++ )
std::cout << matrix[i][j] << " ";
std::cout << std::endl;
}
}
Installing modules usually requires you to run an sql script that is included with the database installation.
Assuming linux-like OS
find / -name dblink.sql
Verify the location and run it
You could use jQuery and an Ajax call to post the specific update back to your server with Javascript.
It would look something like this:
function updatePostID(val, comment)
{
var args = {};
args.PostID = val;
args.Comment = comment;
$.ajax({
type: "POST",
url: controllerActionMethodUrlHere,
contentType: "application/json; charset=utf-8",
data: args,
dataType: "json",
success: function(msg)
{
// Something afterwards here
}
});
}
First, close all instances of Google Chrome. There should be no instances of chrome.exe
running in the Windows Task Manager. Then
%LOCALAPPDATA%\Google\Chrome\User Data\Default\
..txt
). This will serve as a backup, should something go wrong.window_placement
. Under window_placement
you will see things like "bottom", "left", "right", etc. with numbers after them.You will need to play around with these numbers to get your desired window size and placement. When finished, save this file with the name "Preferences" again with no extension. This will overwrite the existing Preferences file. Open Chrome and see how you did. If you're not satisfied with the size and placement, close Chrome and change the numbers in the Preferences file until you get what you want.
I have not seen the approach I use (and have grown to like) posted in any answers, so here it is:
I don't like using static initializers because they are clunky, and I don't like anonymous classes because it is creating a new class for each instance.
instead, I prefer initialization that looks like this:
map(
entry("keyA", "val1"),
entry("keyB", "val2"),
entry("keyC", "val3")
);
unfortunately, these methods are not part of the standard Java library, so you will need to create (or use) a utility library that defines the following methods:
public static <K,V> Map<K,V> map(Map.Entry<K, ? extends V>... entries)
public static <K,V> Map.Entry<K,V> entry(K key, V val)
(you can use 'import static' to avoid needing to prefix the method's name)
I found it useful to provide similar static methods for the other collections (list, set, sortedSet, sortedMap, etc.)
Its not quite as nice as json object initialization, but it's a step in that direction, as far as readability is concerned.
Short answer: use an unassigned user port
Over achiever's answer - Select and deploy a resource discovery solution. Have the server select a private port dynamically. Have the clients use resource discovery.
The risk that that a server will fail because the port it wants to listen on is not available is real; at least it's happened to me. Another service or a client might get there first.
You can almost totally reduce the risk from a client by avoiding the private ports, which are dynamically handed out to clients.
The risk that from another service is minimal if you use a user port. An unassigned port's risk is only that another service happens to be configured (or dyamically) uses that port. But at least that's probably under your control.
The huge doc with all the port assignments, including User Ports, is here: http://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.txt look for the token Unassigned.
Use Access's VBA function Replace(text, find, replacement)
:
Dim result As String
result = Replace("Some sentence containing Avenue in it.", "Avenue", "Ave")
Use this function to get random numbers between given range
function rnd(min,max){
return Math.floor(Math.random()*(max-min+1)+min );
}
mail -s "Your Subject" [email protected] < /file/with/mail/content
(/file/with/mail/content
should be a plaintext file, not a file attachment or an image, etc)
Old question but.. I also needed a periodical task runner and wrote TaskTimer. This is also useful when you need to run multiple tasks on different intervals.
// Timer with 1000ms (1 second) base interval resolution.
const timer = new TaskTimer(1000);
// Add task(s) based on tick intervals.
timer.add({
id: 'job1', // unique id of the task
tickInterval: 5, // run every 5 ticks (5 x interval = 5000 ms)
totalRuns: 10, // run 10 times only. (set to 0 for unlimited times)
callback(task) {
// code to be executed on each run
console.log(task.id + ' task has run ' + task.currentRuns + ' times.');
}
});
// Start the timer
timer.start();
TaskTimer
works both in browser and Node. See documentation for all features.
Your class shoud look something like this:
class Something { int[] array; //global array, replace type of course void function1() { array = new int[10]; //let say you declare it here that will be 10 integers in size } void function2() { array[0] = 12; //assing value at index 0 to 12. } }
That way you array will be accessible in both functions. However, you must be careful with global stuff, as you can quickly overwrite something.
Most browsers will let you put very large amounts of data in a URL and thus lots of things end up creating very large URLs so if you are talking about anything more than the domain part of a URL you will need to use a TEXT column since the VARCHAR/CHAR are limited.
Using Neon - just happened to me too. You would have to delete the Eclipse version (not from disk) in your Project Explorer and import the projects as existing projects. Of course, ensure that the project folders as a whole were moved and that the Eclipse meta files are still there as mentioned by @koenpeters.
Refactor does not handle this.
If you are using maven as build tool for project , build your project properly,your changes in the code and xml files are not reflecting after compilations.
I had this issue. The security settings in the ControlPanel seem to be user specific. Try running it as the user you are actually running your browser as (you are not browsing as root!??) and setting the security level to Medium there. - For me, that did it.
In win7, if you want to set the correct timezone as a parameter in JRE, you have to edit the file deployment.properties
stored in path c:\users\%username%\appdata\locallow\sun\java\deployment
adding the string deployment.javaws.jre.1.args=-Duser.timezone\=
my_time_zone
Put an <audio>
element on your page.
Get your audio element and call the play()
method:
document.getElementById('yourAudioTag').play();
Check out this example: http://www.storiesinflight.com/html5/audio.html
This site uncovers some of the other cool things you can do such as load()
, pause()
, and a few other properties of the audio element.
When exactly you want to play this audio element is up to you. Read the text of the button and compare it to "no" if you like.
http://www.schillmania.com/projects/soundmanager2/
SoundManager 2 provides a easy to use API that allows sound to be played in any modern browser, including IE 6+. If the browser doesn't support HTML5, then it gets help from flash. If you want stricly HTML5 and no flash, there's a setting for that, preferFlash=false
It supports 100% Flash-free audio on iPad, iPhone (iOS4) and other HTML5-enabled devices + browsers
Use is as simple as:
<script src="soundmanager2.js"></script>
<script>
// where to find flash SWFs, if needed...
soundManager.url = '/path/to/swf-files/';
soundManager.onready(function() {
soundManager.createSound({
id: 'mySound',
url: '/path/to/an.mp3'
});
// ...and play it
soundManager.play('mySound');
});
Here's a demo of it in action: http://www.schillmania.com/projects/soundmanager2/demo/christmas-lights/
You have two choices, depending on your table order
create table aa (sht int)
create table cc (sht int)
create table cd (sht int)
create table ab (sht int)
-- type 1
select * from cd
inner join cc on cd.sht = cc.sht
LEFT JOIN ab ON ab.sht = cd.sht
LEFT JOIN aa ON aa.sht = cc.sht
-- type 2
select * from cc
inner join cc on cd.sht = cc.sht
LEFT JOIN ab
LEFT JOIN aa
ON aa.sht = ab.sht
ON ab.sht = cd.sht
Anson's answer will work fine for the simple case, but if you're going to do any more complex date calculations I'd recommend checking out Joda Time. It will make your life much easier.
FYI in Joda Time you could do
DateTime dt = new DateTime();
DateTime fiveDaysEarlier = dt.minusDays(5);
You can use reduce
to loop the array and get the not duplicate values. Also uses an aux object
to get the count of added values.
var aux = {};_x000D_
_x000D_
var newArray = ["X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11", "X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11", "X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11", "X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11", "X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11", "X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11"].reduce((tot, curr)=>{_x000D_
if(!aux[curr]){_x000D_
aux[curr] = 1;_x000D_
tot.push(curr);_x000D_
}_x000D_
return tot;_x000D_
}, []);_x000D_
_x000D_
console.log(newArray);
_x000D_
If you need to do this as part of a script then the best way is to use Java. Assuming the bin directory is in your path (in most cases), you can use the command line:
jar xf test.zip
If Java is not on your path, reference it directly:
C:\Java\jdk1.6.0_03\bin>jar xf test.zip
From my testing using this CSS:
.expandable{
display: none;
}
.expand:hover+.expandable{
display:inline !important;
}
.expandable:hover{
display:inline !important;
}
And this HTML:
<div class="expand">expand</div>
<div class="expand">expand</div>
<div class="expandable">expandable</div>
, it resulted that it does expand using the second , but does not expand using the first one. So if there is a div between the hover target and the hidden div, then it will not work.
It's easy to fit the page if you only have one image. The more challenge task is to fit images with various sizes to a pdf file. The key to archive that is to calculate the aspect ratio of the image and relative width/height ratio of the page. The following code is what I used to convert multiple images online to a PDF file. It will rotate the image(s) based on the orientation of the images/page and set proper margin. My project use images with online src. You should be able to modify to suit your needs.
As for image rotation, if you see a blank page after rotation, it could simply be that the image is out of bounds. See this answer for details.
function exportPdf(urls) {
let pdf = new jsPDF('l', 'mm', 'a4');
const pageWidth = pdf.internal.pageSize.getWidth();
const pageHeight = pdf.internal.pageSize.getHeight();
const pageRatio = pageWidth / pageHeight;
for (let i = 0; i < urls.length; i++) {
let img = new Image();
img.src = urls[i];
img.onload = function () {
const imgWidth = this.width;
const imgHeight = this.height;
const imgRatio = imgWidth / imgHeight;
if (i > 0) { pdf.addPage(); }
pdf.setPage(i + 1);
if (imgRatio >= 1) {
const wc = imgWidth / pageWidth;
if (imgRatio >= pageRatio) {
pdf.addImage(img, 'JPEG', 0, (pageHeight - imgHeight / wc) / 2, pageWidth, imgHeight / wc, null, 'NONE');
}
else {
const pi = pageRatio / imgRatio;
pdf.addImage(img, 'JPEG', (pageWidth - pageWidth / pi) / 2, 0, pageWidth / pi, (imgHeight / pi) / wc, null, 'NONE');
}
}
else {
const wc = imgWidth / pageHeight;
if (1 / imgRatio > pageRatio) {
const ip = (1 / imgRatio) / pageRatio;
const margin = (pageHeight - ((imgHeight / ip) / wc)) / 4;
pdf.addImage(img, 'JPEG', (pageWidth - (imgHeight / ip) / wc) / 2, -(((imgHeight / ip) / wc) + margin), pageHeight / ip, (imgHeight / ip) / wc, null, 'NONE', -90);
}
else {
pdf.addImage(img, 'JPEG', (pageWidth - imgHeight / wc) / 2, -(imgHeight / wc), pageHeight, imgHeight / wc, null, 'NONE', -90);
}
}
if (i == urls.length - 1) {
pdf.save('Photo.pdf');
}
}
}
}
If this is a bit hard to follow, you can also use
.addPage([imgWidth, imgHeight])
, which is more straightforward. The downside of this method is that the first page is fixed bynew jsPDF()
. See this answer for details.
What in the world would a braille keyboard even be??
There are such things as braille writers but you would never use one as an input device for a computer.
If you're simply talking about a keyboard with the braille symbols on it this would also be a very bad idea. You're going to have a lot more keys to reach while typing and it would still be slower.
Touch typing is NOT a visual skill, a blind person can do it just as well as a sighted person.
Line numbers as in number of changed lines or the actual line numbers containing the changes? If you want the number of changed lines, use git diff --stat
. This gives you a display like this:
[me@somehost:~/newsite:master]> git diff --stat
whatever/views/gallery.py | 8 ++++++++
1 files changed, 8 insertions(+), 0 deletions(-)
There is no option to get the line numbers of the changes themselves.
Just a little addition to psycho brm´s answer (his version doesn't work in IE<=8). This code is cross-browser compatible:
function explode (s, separator, limit)
{
var arr = s.split(separator);
if (limit) {
arr.push(arr.splice(limit-1, (arr.length-(limit-1))).join(separator));
}
return arr;
}
I wanted to add something very important. I use JohnnyHK method a lot but I noticed sometimes the changes didn't persist to the database. When I used .markModified
it worked.
User.findOne({username: oldUsername}, function (err, user) {
user.username = newUser.username;
user.password = newUser.password;
user.rights = newUser.rights;
user.markModified(username)
user.markModified(password)
user.markModified(rights)
user.save(function (err) {
if(err) {
console.error('ERROR!');
}
});
});
tell mongoose about the change with doc.markModified('pathToYourDate') before saving.
Just another possibility,
I replaced
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
with
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
and it started without any issues
For a method that works with both C and C++, you might want to consider using the standard library function strtol().
#include <cstdlib>
#include <iostream>
using namespace std;
int main() {
string s = "abcd";
char * p;
long n = strtol( s.c_str(), & p, 16 );
if ( * p != 0 ) { //my bad edit was here
cout << "not a number" << endl;
}
else {
cout << n << endl;
}
}
?:
is the Elvis operator. This is a binary operator which does the following:
Coerces the value left of ?:
to a boolean and checks if it is true
. If true
it will return the expression on the left side, if false it will return the expression on the right side.
var_dump(0 ?: "Expression not true"); // expression returns: Expression not true
var_dump("" ?: "Expression not true"); // expression returns: Expression not true
var_dump("hi" ?: "Expression not true"); // expression returns string hi
var_dump(null ?: "Expression not true"); // expression returns: Expression not true
var_dump(56 ?: "Expression not true"); // expression return int 56
The Elvis operator is basically shorthand syntax for a specific case of the ternary operator which is:
$testedVar ? $ testedVar : $otherVar;
The Elvis operator will make the syntax more consise in the following manner:
$testedVar ?: $otherVar;
Add following dll files to bin folder:
DotNetOpenAuth.AspNet.dll
DotNetOpenAuth.Core.dll
DotNetOpenAuth.OAuth.Consumer.dll
DotNetOpenAuth.OAuth.dll
DotNetOpenAuth.OpenId.dll
DotNetOpenAuth.OpenId.RelyingParty.dll
If you will not need them, delete dependentAssemblies
from config named 'DotNetOpenAuth.Core' etc..
You can use following code snippet
((ch.qos.logback.classic.Logger)LoggerFactory.getLogger(packageName)).setLevel(ch.qos.logback.classic.Level.toLevel(logLevel));
Response you are getting is in object form i.e.
{
"dstOffset" : 3600,
"rawOffset" : 36000,
"status" : "OK",
"timeZoneId" : "Australia/Hobart",
"timeZoneName" : "Australian Eastern Daylight Time"
}
Replace below line of code :
List<Post> postsList = Arrays.asList(gson.fromJson(reader,Post.class))
with
Post post = gson.fromJson(reader, Post.class);
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 50)];
CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = view.bounds;
gradient.colors = @[(id)[UIColor whiteColor].CGColor, (id)[UIColor blackColor].CGColor];
[view.layer insertSublayer:gradient atIndex:0];
let view = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 50))
let gradient = CAGradientLayer()
gradient.frame = view.bounds
gradient.colors = [UIColor.white.cgColor, UIColor.black.cgColor]
view.layer.insertSublayer(gradient, at: 0)
Info: use startPoint and endPoint to change direction of gradient.
If there are any other views added onto this UIView
(such as a UILabel
), you may want to consider setting the background color of those UIView
’s to [UIColor clearColor]
so the gradient view is presented instead of the background color for sub views. Using clearColor
has a slight performance hit.
For simple SVG to PNG conversion I found cairosvg (https://cairosvg.org/) performs better than ImageMagick. Steps for install and running on all SVG files in your directory.
pip3 install cairosvg
Open a python shell in the directory which contains your .svg files and run:
import os
import cairosvg
for file in os.listdir('.'):
name = file.split('.svg')[0]
cairosvg.svg2png(url=name+'.svg',write_to=name+'.png')
This will also ensure you don't overwrite your original .svg files, but will keep the same name. You can then move all your .png files to another directory with:
$ mv *.png [new directory]
I just installed SQL Developer 4.0.0.13 and the SetJavaHome
can now be overridden by a user-specific configuration file (not sure if this is new to 4.0.0.13 or not).
The location of this user-specific configuration file can be seen in the user.conf
property under 'Help -> About' on the 'Properties' tab. For example, mine was set to:
C:\Users\username\AppData\Roaming\sqldeveloper\1.0.0.0.0\product.conf
On Windows 7.
The first section of this file is used to set the JDK that SQLDeveloper should use:
#
# By default, the product launcher will search for a JDK to use, and if none
# can be found, it will ask for the location of a JDK and store its location
# in this file. If a particular JDK should be used instead, uncomment the
# line below and set the path to your preferred JDK.
#
SetJavaHome C:\Program Files (x86)\Java\jdk1.7.0_03
This setting overrides the setting in sqldeveloper.conf
Additionally, how do I retrieve the number of days of a given month?
Aside from calculating it yourself (and consequently having to get leap years right), you can use a Date calculation to do it:
var y= 2010, m= 11; // December 2010 - trap: months are 0-based in JS
var next= Date.UTC(y, m+1); // timestamp of beginning of following month
var end= new Date(next-1); // date for last second of this month
var lastday= end.getUTCDate(); // 31
In general for timestamp/date calculations I'd recommend using the UTC-based methods of Date, like getUTCSeconds
instead of getSeconds()
, and Date.UTC
to get a timestamp from a UTC date, rather than new Date(y, m)
, so you don't have to worry about the possibility of weird time discontinuities where timezone rules change.
update the rubygems
gem update --system
Please try this one..
JSONObject jsonObject= null;
try {
jsonObject = new JSONObject("result........");
String labelDataString=jsonObject.getString("LabelData");
JSONObject labelDataJson= null;
labelDataJson= new JSONObject(labelDataString);
if(labelDataJson.has("video")&&labelDataJson.getString("video")!=null){
String video=labelDataJson.getString("video");
}
} catch (JSONException e) {
e.printStackTrace();
}
window.top.location.href = "http://example.com";
window.top
refers to the window object of the page at the top of the frames hierarchy.
The pickle (and gzip if the file is compressed) module need to be used
NOTE: These are already in the standard Python library. No need to install anything new
You can push data from the server to the browser via Server Side Events. This is essentially a unidirectional stream that a client can "subscribe" to from a browser. From here, you could just create new Notification
objects as SSEs stream into the browser:
var source = new EventSource('/events');
source.on('message', message => {
var notification = new Notification(message.title, {
body: message.body
});
});
A bit old, but this article by Eric Bidelman explains the basics of SSE and provides some server code examples as well.
Hope it helps!
package join;
public class ThreadJoinApp {
Thread th = new Thread("Thread 1") {
public void run() {
System.out.println("Current thread execution - " + Thread.currentThread().getName());
for (int i = 0; i < 10; i++) {
System.out.println("Current thread execution - " + Thread.currentThread().getName() + " at index - " + i);
}
}
};
Thread th2 = new Thread("Thread 2") {
public void run() {
System.out.println("Current thread execution - " + Thread.currentThread().getName());
//Thread 2 waits until the thread 1 successfully completes.
try {
th.join();
} catch( InterruptedException ex) {
System.out.println("Exception has been caught");
}
for (int i = 0; i < 10; i++) {
System.out.println("Current thread execution - " + Thread.currentThread().getName() + " at index - " + i);
}
}
};
public static void main(String[] args) {
ThreadJoinApp threadJoinApp = new ThreadJoinApp();
threadJoinApp.th.start();
threadJoinApp.th2.start();
}
//Happy coding -- Parthasarathy S
}
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Uri uri = Uri.fromParts("package", getPackageName(), null);
intent.setData(uri);
startActivity(intent);
Description
Settings.ACTION_APPLICATION_DETAILS_SETTINGS
Opens Details setting page for App. From here user have to manually assign desired permission.
Intent.FLAG_ACTIVITY_NEW_TASK
Optional. If set then opens Settings Screen(Activity) as new activity. Otherwise, it will be opened in currently running activity.
Uri.fromParts("package", getPackageName(), null)
Prepares or creates URI, whereas, getPackageName() - returns name of your application package.
intent.setData(uri)
Don't forget to set this. Otherwise, you will get android.content.ActivityNotFoundException
. Because you have set your intent as Settings.ACTION_APPLICATION_DETAILS_SETTINGS
and android expects some name to search.
To use $variables
inside your calc()
of the height property:
HTML:
<div></div>
SCSS:
$a: 4em;
div {
height: calc(#{$a} + 7px);
background: #e53b2c;
}
Try this theme
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
<item name="colorPrimaryDark">@android:color/transparent</item>
<item name="colorPrimary">@color/md_blue_200</item>
<item name="android:windowDrawsSystemBarBackgrounds">true</item>
<item name="android:statusBarColor">@android:color/transparent</item>
<item name="android:windowTranslucentStatus">true</item>
</style>
Be sure that, your layout set
android:fitsSystemWindows="false"
In addition to what has already been said I also like to add a different approach and advocate the use of differential script deployment strategy. Instead of making a stateful script that always checks the current state and acts based on that state, deploy via a series of stateless scripts that upgrade from well known versions. I have used this strategy and it pays off big time as my deployment scripts are now all 'IF' free.
This is in answer to your question...
I'd also like to know how to make it open up in Sublime Text 2 instead
For Windows:
git config --global core.editor "'C:/Program Files/Sublime Text 2/sublime_text.exe'"
Check that the path for sublime_text.exe
is correct and adjust if needed.
For Mac/Linux:
git config --global core.editor "subl -n -w"
If you get an error message such as:
error: There was a problem with the editor 'subl -n -w'.
Create the alias for subl
sudo ln -s /Applications/Sublime\ Text.app/Contents/SharedSupport/bin/subl /usr/local/bin/subl
Again check that the path matches for your machine.
For Sublime Text simply save cmd S
and close the window cmd W
to return to git.
Here's the GNU version of printf
... you can see it passing in stdout
to vfprintf
:
__printf (const char *format, ...)
{
va_list arg;
int done;
va_start (arg, format);
done = vfprintf (stdout, format, arg);
va_end (arg);
return done;
}
Here's a link to vfprintf
... all the formatting 'magic' happens here.
The only thing that's truly 'different' about these functions is that they use varargs to get at arguments in a variable length argument list. Other than that, they're just traditional C. (This is in contrast to Pascal's printf
equivalent, which is implemented with specific support in the compiler... at least it was back in the day.)
One more thing that I would definitely like to highlight as logit is just a raw output, generally the output of last layer. This can be a negative value as well. If we use it as it's for "cross entropy" evaluation as mentioned below:
-tf.reduce_sum(y_true * tf.log(logits))
then it wont work. As log of -ve is not defined. So using o softmax activation, will overcome this problem.
This is my understanding, please correct me if Im wrong.
Put a div
inside td
and give following style width:50px;overflow: hidden;
to the div
Jsfiddle link
<td>
<div style="width:50px;overflow: hidden;">
<span>A long string more than 50px wide</span>
</div>
</td>
For anyone having issues with Visual Studio 2019:
I had to first open menu Test ? Windows ? Test Explorer, and run the tests from there, before the option to Run / Debug tests would show up on the right click menu.
You need to use the autoGenerate
property
Your primary key annotation should be like this:
@PrimaryKey(autoGenerate = true)
Reference for PrimaryKey.
Whatever urllib is using to figure out Content-Length seems to get confused by json, so you have to calculate that yourself.
import json
import urllib2
data = json.dumps([1, 2, 3])
clen = len(data)
req = urllib2.Request(url, data, {'Content-Type': 'application/json', 'Content-Length': clen})
f = urllib2.urlopen(req)
response = f.read()
f.close()
Took me for ever to figure this out, so I hope it helps someone else.
On a Mac, the idea.log is contained in
/Users/<user>/Library/Logs/AndroidStudio/idea.log
The new stable version (1.2) is in
/Users/<user>/Library/Logs/AndroidStudio1.2/
The new stable version (2.2) is in
/Users/<user>/Library/Logs/AndroidStudio2.2/
The new stable version (3.4) is in
/Users/<user>/Library/Logs/AndroidStudio3.4/
I had this error too, my problem was in some part of code I didn't close file descriptor and in other part, I tried to open that file!!
use close(fd)
system call after you finished working on a file.
I did more simple (positive way) and it seems to work well.
Since any kind of "object" is at least an object
if (MyObj is Object)
{
//Do something .... for example:
if (MyObj is Button)
MyObj.Enabled = true;
}
In Python 3.x and 2.7, you can simply do this:
>>> '${:,.2f}'.format(1234.5)
'$1,234.50'
The :,
adds a comma as a thousands separator, and the .2f
limits the string to two decimal places (or adds enough zeroes to get to 2 decimal places, as the case may be) at the end.
You have some files locally that need to be merged before you can pull. You could checkout the files and then pull to overwrite your local files.
git checkout app/config/app.php app/config/database.php app/routes.php
git pull origin master
0.01 is not an integer (whole number), so you of course can't parse it as one. Use Double.parseDouble
or Float.parseFloat
instead.
You have to put your script tag after the one that references Angular. Move it out of the head
:
<script type="text/javascript" src="angular.min.js"></script>
<script type="text/javascript" src="main.js"></script>
The way you've set it up now, your script runs before Angular is loaded on the page.
Are you providing write input to the console ?
Scanner reader = new Scanner(System.in);
num = reader.nextDouble();
This is return double if you just enter number like 456. In case you enter a string or character instead,it will throw java.util.InputMismatchException when it tries to do num = reader.nextDouble() .
You can use pydash:
import pydash as _
_.get(dataDict, ["b", "v", "y"], default='Default')
git-clean
Use to remove untracked files in the working tree. Following are some options (in brief) that can use with git clean
command.
-d
use when no path is specified. So git recurse into untracked directories remove them.
-f/--force
To remove nested untracked files.
-i/--interactive
Show what would be done and clean files interactively.
-n/--dry-run
Show what will happen without removing anything.
-x
ignore files
example: git clean -f -d
-> Remove all untracked files in current directory any subdirectories.
The Chrome CSS property -webkit-print-color-adjust: exact;
works appropriately.
However, making sure you have the correct CSS for printing can often be tricky. Several things can be done to avoid the difficulties you are having. First, separate all your print CSS from your screen CSS. This is done via the @media print
and @media screen
.
Often times just setting up some extra @media print
CSS is not enough because you still have all your other CSS included when printing as well. In these cases you just need to be aware of CSS specificity as the print rules don't automatically win against non-print CSS rules.
In your case, the -webkit-print-color-adjust: exact
is working. However, your background-color
and color definitions are being beaten out by other CSS with higher specificity.
While I do not endorse using !important
in nearly any circumstance, the following definitions work properly and expose the problem:
@media print {
tr.vendorListHeading {
background-color: #1a4567 !important;
-webkit-print-color-adjust: exact;
}
}
@media print {
.vendorListHeading th {
color: white !important;
}
}
Here is the fiddle (and embedded for ease of print previewing).
move you mouse over the "Hello, playground" on the right side bar, you will see an eye icon and a small circle icon next it. Just click on the circle one to show the detail page and console output!
To UrlEncode without using System.Web:
String s = System.Net.WebUtility.UrlEncode(str);
//fix some different between WebUtility.UrlEncode and HttpUtility.UrlEncode
s = Regex.Replace(s, "(%[0-9A-F]{2})", c => c.Value.ToLowerInvariant());
more details: https://www.samnoble.co.uk/2014/05/21/beware-webutility-urlencode-vs-httputility-urlencode/
PowerShell (Core-compatible) one-liner to ease copypaste scenarios:
netstat -aon | Select-String 8080 | ForEach-Object { $_ -replace '\s+', ',' } | ConvertFrom-Csv -Header @('Empty', 'Protocol', 'AddressLocal', 'AddressForeign', 'State', 'PID') | ForEach-Object { $portProcess = Get-Process | Where-Object Id -eq $_.PID; $_ | Add-Member -NotePropertyName 'ProcessName' -NotePropertyValue $portProcess.ProcessName; Write-Output $_ } | Sort-Object ProcessName, State, Protocol, AddressLocal, AddressForeign | Select-Object ProcessName, State, Protocol, AddressLocal, AddressForeign | Format-Table
Output:
ProcessName State Protocol AddressLocal AddressForeign
----------- ----- -------- ------------ --------------
System LISTENING TCP [::]:8080 [::]:0
System LISTENING TCP 0.0.0.0:8080 0.0.0.0:0
Same code, developer-friendly:
$Port = 8080
# Get PID's listening to $Port, as PSObject
$PidsAtPortString = netstat -aon `
| Select-String $Port
$PidsAtPort = $PidsAtPortString `
| ForEach-Object { `
$_ -replace '\s+', ',' `
} `
| ConvertFrom-Csv -Header @('Empty', 'Protocol', 'AddressLocal', 'AddressForeign', 'State', 'PID')
# Enrich port's list with ProcessName data
$ProcessesAtPort = $PidsAtPort `
| ForEach-Object { `
$portProcess = Get-Process `
| Where-Object Id -eq $_.PID; `
$_ | Add-Member -NotePropertyName 'ProcessName' -NotePropertyValue $portProcess.ProcessName; `
Write-Output $_;
}
# Show output
$ProcessesAtPort `
| Sort-Object ProcessName, State, Protocol, AddressLocal, AddressForeign `
| Select-Object ProcessName, State, Protocol, AddressLocal, AddressForeign `
| Format-Table