/*
public class UserDAO {
public boolean insertUser(UserBean u) {
boolean flag = false;
MySqlConnection msq = new MySqlConnection();
try {
String sql = "insert into regis values(?,?,?,?,?)";
Connection connection = msq.getConnection();
PreparedStatement statement = null;
statement = (PreparedStatement) connection.prepareStatement(sql);
statement.setString(1, u.getname());
statement.setString(2, u.getlname());
statement.setString(3, u.getemail());
statement.setString(4, u.getusername());
statement.setString(5, u.getpasswords());
statement.executeUpdate();
flag = true;
} catch (Exception e) {
} finally {
return flag;
}
}
public String userValidate(UserBean u) {
String login = "";
MySqlConnection msq = new MySqlConnection();
try {
String email = u.getemail();
String Pass = u.getpasswords();
String sql = "SELECT name FROM regis WHERE email=? and passwords=?";
com.mysql.jdbc.Connection connection = msq.getConnection();
com.mysql.jdbc.PreparedStatement statement = null;
ResultSet rs = null;
statement = (com.mysql.jdbc.PreparedStatement) connection.prepareStatement(sql);
statement.setString(1, email);
statement.setString(2, Pass);
rs = statement.executeQuery();
if (rs.next()) {
login = rs.getString("name");
} else {
login = "false";
}
} catch (Exception e) {
} finally {
return login;
}
}
public boolean getmessage(UserBean u) {
boolean flag = false;
MySqlConnection msq = new MySqlConnection();
try {
String sql = "insert into feedback values(?,?)";
Connection connection = msq.getConnection();
PreparedStatement statement = null;
statement = (PreparedStatement) connection.prepareStatement(sql);
statement.setString(1, u.getemail());
statement.setString(2, u.getfeedback());
statement.executeUpdate();
flag = true;
} catch (Exception e) {
} finally {
return flag;
}
}
public boolean insertOrder(cartbean u) {
boolean flag = false;
MySqlConnection msq = new MySqlConnection();
try {
String sql = "insert into cart (product_id, email, Tprice, quantity) values (?,?,2000,?)";
Connection connection = msq.getConnection();
PreparedStatement statement = null;
statement = (PreparedStatement) connection.prepareStatement(sql);
statement.setString(1, u.getpid());
statement.setString(2, u.getemail());
statement.setString(3, u.getquantity());
statement.executeUpdate();
flag = true;
} catch (Exception e) {
System.out.print("hi");
} finally {
return flag;
}
}
}
?$(document).ready(function(){
$('#foo').bind('mousewheel', function(e){
if(e.originalEvent.wheelDelta /120 > 0) {
console.log('scrolling up !');
}
else{
console.log('scrolling down !');
}
});
});
Below is code that I currently use to pull data from a MS SQL Server 2008 into VBA. You need to make sure you have the proper ADODB reference [VBA Editor->Tools->References] and make sure you have Microsoft ActiveX Data Objects 2.8 Library checked, which is the second from the bottom row that is checked (I'm using Excel 2010 on Windows 7; you might have a slightly different ActiveX version, but it will still begin with Microsoft ActiveX):
Sub Module for Connecting to MS SQL with Remote Host & Username/Password
Sub Download_Standard_BOM()
'Initializes variables
Dim cnn As New ADODB.Connection
Dim rst As New ADODB.Recordset
Dim ConnectionString As String
Dim StrQuery As String
'Setup the connection string for accessing MS SQL database
'Make sure to change:
'1: PASSWORD
'2: USERNAME
'3: REMOTE_IP_ADDRESS
'4: DATABASE
ConnectionString = "Provider=SQLOLEDB.1;Password=PASSWORD;Persist Security Info=True;User ID=USERNAME;Data Source=REMOTE_IP_ADDRESS;Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Use Encryption for Data=False;Tag with column collation when possible=False;Initial Catalog=DATABASE"
'Opens connection to the database
cnn.Open ConnectionString
'Timeout error in seconds for executing the entire query; this will run for 15 minutes before VBA timesout, but your database might timeout before this value
cnn.CommandTimeout = 900
'This is your actual MS SQL query that you need to run; you should check this query first using a more robust SQL editor (such as HeidiSQL) to ensure your query is valid
StrQuery = "SELECT TOP 10 * FROM tbl_table"
'Performs the actual query
rst.Open StrQuery, cnn
'Dumps all the results from the StrQuery into cell A2 of the first sheet in the active workbook
Sheets(1).Range("A2").CopyFromRecordset rst
End Sub
Yes, you can find out element by data attribute.
element = $('a[data-item-id="stand-out"]');
Here one check is required that the url going to be open is able to open by device or simulator or not. Because some times (majority in simulator) i found it causes crashes.
Objective-C
NSURL *url = [NSURL URLWithString:@"some url"];
if ([[UIApplication sharedApplication] canOpenURL:url]) {
[[UIApplication sharedApplication] openURL:url];
}
Swift 2.0
let url : NSURL = NSURL(string: "some url")!
if UIApplication.sharedApplication().canOpenURL(url) {
UIApplication.sharedApplication().openURL(url)
}
Swift 4.2
guard let url = URL(string: "some url") else {
return
}
if UIApplication.shared.canOpenURL(url) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
}
Reversed order digit extractor (eg. for 23 will be 3 and 2):
while (number > 0)
{
int digit = number%10;
number /= 10;
//print digit
}
Normal order digit extractor (eg. for 23 will be 2 and 3):
std::stack<int> sd;
while (number > 0)
{
int digit = number%10;
number /= 10;
sd.push(digit);
}
while (!sd.empty())
{
int digit = sd.top();
sd.pop();
//print digit
}
Other than white-space:nowrap;
also add the following CSS
ul li{
display: inline;
}
If you're using a std::string
, call length()
:
std::string str = "hello";
std::cout << str << ":" << str.length();
// Outputs "hello:5"
If you're using a c-string, call strlen()
.
const char *str = "hello";
std::cout << str << ":" << strlen(str);
// Outputs "hello:5"
Or, if you happen to like using Pascal-style strings (or f***** strings as Joel Spolsky likes to call them when they have a trailing NULL), just dereference the first character.
const char *str = "\005hello";
std::cout << str + 1 << ":" << *str;
// Outputs "hello:5"
Great answer above. Another way is to use the great yaml jq wrapper tool, yq at https://github.com/kislyuk/yq
Save your JSON example to a file, say ex.json and then
yq -y '.' ex.json
AAPL:
- shares: -75.088
date: 11/27/2015
- shares: 75.088
date: 11/26/2015
To add to the other answers, Cygwin comes with the MinGW libraries and headers and you can compile without linking to the cygwin1.dll by using -mno-cygwin flag with gcc. I greatly prefer this to using plain MinGW and MSYS.
import math
number = int(input("Enter number to print: "))
number_list = ["zero","one","two","three","four","five","six","seven","eight","nine"]
teen_list = ["ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"]
decades_list =["twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"]
if number <= 9:
print(number_list[number].capitalize())
elif number >= 10 and number <= 19:
tens = number % 10
print(teen_list[tens].capitalize())
elif number > 19 and number <= 99:
ones = math.floor(number/10)
twos = ones - 2
tens = number % 10
if tens == 0:
print(decades_list[twos].capitalize())
elif tens != 0:
print(decades_list[twos].capitalize() + " " + number_list[tens])
This member fn returns an array of 0-based positions, if any, of the input word inside the String object
String.prototype.matching_positions = function( _word, _case_sensitive, _whole_words, _multiline )
{
/*besides '_word' param, others are flags (0|1)*/
var _match_pattern = "g"+(_case_sensitive?"i":"")+(_multiline?"m":"") ;
var _bound = _whole_words ? "\\b" : "" ;
var _re = new RegExp( _bound+_word+_bound, _match_pattern );
var _pos = [], _chunk, _index = 0 ;
while( true )
{
_chunk = _re.exec( this ) ;
if ( _chunk == null ) break ;
_pos.push( _chunk['index'] ) ;
_re.lastIndex = _chunk['index']+1 ;
}
return _pos ;
}
Now try
var _sentence = "What do doers want ? What do doers need ?" ;
var _word = "do" ;
console.log( _sentence.matching_positions( _word, 1, 0, 0 ) );
console.log( _sentence.matching_positions( _word, 1, 1, 0 ) );
You can also input regular expressions:
var _second = "z^2+2z-1" ;
console.log( _second.matching_positions( "[0-9]\z+", 0, 0, 0 ) );
Here one gets the position index of linear term.
I started getting this error (different stack trace though) after making a trivial update to my GraphQL API application that is operated inside a docker container. For whatever reason, the container was having difficulty resolving a back-end service being used by the API.
After poking around to see if some change had been made in the docker base image I was building from (node:13-alpine, incidentally), I decided to try the oldest computer science trick of rebooting... I stopped and started the docker container and all went back to normal.
Clearly, this isn't a meaningful solution to the underlying problem - I am merely posting this since it did clear up the issue for me without going too deep down rabbit holes.
We can add java folder from
It works fine.
It is a 32bit declaration. If you type at the top of an assembly file the statement [bits 32], then you don't need to type DWORD PTR. So for example:
[bits 32]
.
.
and [ebp-4], 0
I wrote a bash script that looks at the type of a file then copies it to a location, I use it to look through the videos I've watched online from my firefox cache:
#!/bin/bash
# flvcache script
CACHE=~/.mozilla/firefox/xxxxxxxx.default/Cache
OUTPUTDIR=~/Videos/flvs
MINFILESIZE=2M
for f in `find $CACHE -size +$MINFILESIZE`
do
a=$(file $f | cut -f2 -d ' ')
o=$(basename $f)
if [ "$a" = "Macromedia" ]
then
cp "$f" "$OUTPUTDIR/$o"
fi
done
nautilus "$OUTPUTDIR"&
It uses similar ideas to those presented here, hope this is helpful to someone.
Use Apache Commons StringUtils:
StringUtils.containsWhitespace(str)
In MYSQL we have function called DATE_FORMAT(date,format). In your case your select statement will become like this:-
SELECT DATE_FORMAT(dateTimeFieldName,"%a%m%Y") as dateFieldName FROM table_name
For more information about Mysql DATE and TIME functions click here.
I can see the that the others answers shown above are right, but I'll make your life easy.
I even created an example for you. I added some rows and want delete them.
You have to right click on the table and as shown in the figure Script Table a> Delete to> New query Editor widows:
Then another window will open with a script. Delete the line of "where", because you want to delete all rows. Then click Execute.
To make sure you did it right right click over the table and click in "Select Top 1000 rows". Then you can see that the query is empty.
Hope this helps: http://nrecursions.blogspot.in/2014/02/how-to-trigger-jenkins-build-on-git.html
It's just a matter of using curl
to trigger a Jenkins job using the git hooks provided by git.
The command
curl http://localhost:8080/job/someJob/build?delay=0sec
can run a Jenkins job, where someJob
is the name of the Jenkins job.
Search for the hooks
folder in your hidden .git folder. Rename the post-commit.sample
file to post-commit
. Open it with Notepad, remove the : Nothing
line and paste the above command into it.
That's it. Whenever you do a commit, Git will trigger the post-commit commands defined in the file.
I fixed it with adding the prefix (attr.) :
<create-report-card-form [attr.currentReportCardCount]="expression" ...
Unfortunately this haven't documented properly yet.
more detail here
public class RemoveDecimalPoint{
public static void main(String []args){
System.out.println(""+ removePoint(250022005.60));
}
public static String removePoint(double number) {
long x = (long) number;
return x+"";
}
}
The window.open
will open url in new browser Tab
The window.location.href
will open url in current Tab (instead you can use location
)
Here is example fiddle (in SO snippets window.open doesn't work)
var url = 'https://example.com';_x000D_
_x000D_
function go1() { window.open(url) }_x000D_
_x000D_
function go2() { window.location.href = url }_x000D_
_x000D_
function go3() { location = url }
_x000D_
<div>Go by:</div>_x000D_
<button onclick="go1()">window.open</button>_x000D_
<button onclick="go2()">window.location.href</button>_x000D_
<button onclick="go3()">location</button>
_x000D_
For some databases, you can just explicitly insert a NULL
into the auto_increment
column:
INSERT INTO table_name VALUES (NULL, 'my name', 'my group')
With the command:
sudo apt-get remove --purge mysql\*
you can delete anything related to packages named mysql. Those commands are only valid on debian / debian-based linux distributions (Ubuntu for example).
You can list all installed mysql packages with the command:
sudo dpkg -l | grep -i mysql
For more cleanup of the package cache, you can use the command:
sudo apt-get clean
Also, remember to use the command:
sudo updatedb
Otherwise the "locate" command will display old data.
To install mysql again, use the following command:
sudo apt-get install libmysqlclient-dev mysql-client
This will install the mysql client, libmysql and its headers files.
To install the mysql server, use the command:
sudo apt-get install mysql-server
If you only need to find a free port for later use, here is a snippet similar to a previous answer, but shorter, using socketserver:
import socketserver
with socketserver.TCPServer(("localhost", 0), None) as s:
free_port = s.server_address[1]
Note that the port is not guaranteed to remain free, so you may need to put this snippet and the code using it in a loop.
The split method of a string is what you need. In fact the tokenizer class in Java is deprecated in favor of Java's string split method.
Maven acts as both a dependency management tool - it can be used to retrieve jars from a central repository or from a repository you set up - and as a declarative build tool. The difference between a "declarative" build tool and a more traditional one like ant or make is you configure what needs to get done, not how it gets done. For example, you can say in a maven script that a project should be packaged as a WAR file, and maven knows how to handle that.
Maven relies on conventions about how project directories are laid out in order to achieve its "declarativeness." For example, it has a convention for where to put your main code, where to put your web.xml, your unit tests, and so on, but also gives the ability to change them if you need to.
You should also keep in mind that there is a plugin for running ant commands from within maven:
http://maven.apache.org/plugins/maven-ant-plugin/
Also, maven's archetypes make getting started with a project really fast. For example, there is a Wicket archetype, which provides a maven command you run to get a whole, ready-to-run hello world-type project.
Map#merge
As of java-8 you can use Map#merge(K key, V value, BiFunction remappingFunction)
which merges a value into the Map
using remappingFunction
in case the key is already found in the Map
you want to put the pair into.
// using lambda
newMap.forEach((key, value) -> map.merge(key, value, (oldValue, newValue) -> oldValue));
// using for-loop
for (Map.Entry<Integer, String> entry: newMap.entrySet()) {
map.merge(entry.getKey(), entry.getValue(), (oldValue, newValue) -> oldValue);
}
The code iterates the newMap
entries (key
and value
) and each one is merged into map
through the method merge
. The remappingFunction
is triggered in case of duplicated key and in that case it says that the former (original) oldValue
value will be used and not rewritten.
With this solution, you don't need a temporary Map
.
Let's have an example of merging newMap
entries into map
and keeping the original values in case of the duplicated antry.
Map<Integer, String> newMap = new HashMap<>();
newMap.put(2, "EVIL VALUE"); // this will NOT be merged into
newMap.put(4, "four"); // this WILL be merged into
newMap.put(5, "five"); // this WILL be merged into
Map<Integer, String> map = new HashMap<>();
map.put(1, "one");
map.put(2, "two");
map.put(3, "three");
newMap.forEach((k, v) -> map.merge(k, v, (oldValue, newValue) -> oldValue));
map.forEach((k, v) -> System.out.println(k + " " + v));
1 one 2 two 3 three 4 four 5 five
Well, not always. Using cookies, you are good. But the "can I safely rely on the id being present" urged me to extend the discussion with an important point (mostly for reference, as the visitor count of this page seems quite high).
PHP can be configured to maintain sessions by URL-rewriting, instead of cookies. (How it's good or bad (<-- see e.g. the topmost comment there) is a separate question, let's now stick to the current one, with just one side-note: the most prominent issue with URL-based sessions -- the blatant visibility of the naked session ID -- is not an issue with internal Ajax calls; but then, if it's turned on for Ajax, it's turned on for the rest of the site, too, so there...)
In case of URL-rewriting (cookieless) sessions, Ajax calls must take care of it themselves that their request URLs are properly crafted. (Or you can roll your own custom solution. You can even resort to maintaining sessions on the client side, in less demanding cases.) The point is the explicit care needed for session continuity, if not using cookies:
If the Ajax calls just extract URLs verbatim from the HTML (as received from PHP), that should be OK, as they are already cooked (umm, cookified).
If they need to assemble request URIs themselves, the session ID needs to be added to the URL manually. (Check here, or the page sources generated by PHP (with URL-rewriting on) to see how to do it.)
From OWASP.org:
Effectively, the web application can use both mechanisms, cookies or URL parameters, or even switch from one to the other (automatic URL rewriting) if certain conditions are met (for example, the existence of web clients without cookies support or when cookies are not accepted due to user privacy concerns).
From a Ruby-forum post:
When using php with cookies, the session ID will automatically be sent in the request headers even for Ajax XMLHttpRequests. If you use or allow URL-based php sessions, you'll have to add the session id to every Ajax request url.
You must have an empty line in your file.
You may want to wrap your parseInt calls in a "try" block:
try {
tall[i++] = Integer.parseInt(s);
}
catch (NumberFormatException ex) {
continue;
}
Or simply check for empty strings before parsing:
if (s.length() == 0)
continue;
Note that by initializing your index variable i
inside the loop, it is always 0. You should move the declaration before the while
loop. (Or make it part of a for
loop.)
maybe it is caused by privilege, please try this:
#sudo chmod 755 /Applications
#sudo chmod 755 /Applications/Virtualbox.app
Make sure that you're using the same host in the URL that you were when you set up the mapping. E.g. if you were at http://127.0.0.1/my-app
when you set up and mapped the workspace then breakpoints won't work if you view the page via http://localhost/my-app
.
Also, thanks for reading this far. See my answer to the Chromium issue here.
This is the class I came up with in the end:
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
/**
* Utility class for JavaScript compatible UTF-8 encoding and decoding.
*
* @see http://stackoverflow.com/questions/607176/java-equivalent-to-javascripts-encodeuricomponent-that-produces-identical-output
* @author John Topley
*/
public class EncodingUtil
{
/**
* Decodes the passed UTF-8 String using an algorithm that's compatible with
* JavaScript's <code>decodeURIComponent</code> function. Returns
* <code>null</code> if the String is <code>null</code>.
*
* @param s The UTF-8 encoded String to be decoded
* @return the decoded String
*/
public static String decodeURIComponent(String s)
{
if (s == null)
{
return null;
}
String result = null;
try
{
result = URLDecoder.decode(s, "UTF-8");
}
// This exception should never occur.
catch (UnsupportedEncodingException e)
{
result = s;
}
return result;
}
/**
* Encodes the passed String as UTF-8 using an algorithm that's compatible
* with JavaScript's <code>encodeURIComponent</code> function. Returns
* <code>null</code> if the String is <code>null</code>.
*
* @param s The String to be encoded
* @return the encoded String
*/
public static String encodeURIComponent(String s)
{
String result = null;
try
{
result = URLEncoder.encode(s, "UTF-8")
.replaceAll("\\+", "%20")
.replaceAll("\\%21", "!")
.replaceAll("\\%27", "'")
.replaceAll("\\%28", "(")
.replaceAll("\\%29", ")")
.replaceAll("\\%7E", "~");
}
// This exception should never occur.
catch (UnsupportedEncodingException e)
{
result = s;
}
return result;
}
/**
* Private constructor to prevent this class from being instantiated.
*/
private EncodingUtil()
{
super();
}
}
I had the same issue today using primefaces (primeng) and angular 7. Add the following to your style.css
p-button {
-webkit-appearance: none !important;
}
i am also using a bit of bootstrap which has a reboot.css, that overrides it with (thats why i had to add !important)
button {
-webkit-appearance: button;
}
split with the + sign like this way
String a = tv.getText().toString();
String aa[];
if(a.contains("+"))
aa = a.split("+");
now convert the array
Integer.parseInt(aa[0]); // and so on
Concurrent signal assignment:
library ieee;
use ieee.std_logic_1164.all;
entity foo is
end;
architecture behave of foo is
signal clk: std_logic := '0';
begin
CLOCK:
clk <= '1' after 0.5 ns when clk = '0' else
'0' after 0.5 ns when clk = '1';
end;
ghdl -a foo.vhdl
ghdl -r foo --stop-time=10ns --wave=foo.ghw
ghdl:info: simulation stopped by --stop-time
gtkwave foo.ghw
Simulators simulate processes and it would be transformed into the equivalent process to your process statement. Simulation time implies the use of wait for or after when driving events for sensitivity clauses or sensitivity lists.
Use Enum
's static method, GetNames
. It returns a string[]
, like so:
Enum.GetNames(typeof(DataSourceTypes))
If you want to create a method that does only this for only one type of enum
, and also converts that array to a List
, you can write something like this:
public List<string> GetDataSourceTypes()
{
return Enum.GetNames(typeof(DataSourceTypes)).ToList();
}
You will need Using System.Linq;
at the top of your class to use .ToList()
script(nonce="some-nonce").
console.log("test");
//- Workaround
<script nonce="some-nonce">console.log("test");</script>
I tried with this in the context field:
this.getActivity().getParent()
and it works fine for me. This was from a class which extends from "Fragment":
public class filtro extends Fragment{...
You can use the username variable: %USERNAME%
SQL Developer seems to only output the DBMS_OUTPUT text when you have explicitly turned on the DBMS_OUTPUT window pane.
Go to (Menu) VIEW -> Dbms_output to invoke the pane.
Click on the Green Plus sign to enable output for your connection and then run the code.
EDIT: Don't forget to set the buffer size according to the amount of output you are expecting.
Download the latest CMake Mac binary distribution here: https://cmake.org/download/ (current latest is: https://cmake.org/files/v3.17/cmake-3.17.1-Darwin-x86_64.dmg)
Double click the downloaded .dmg file to install it. In the window that pops up, drag the CMake icon into the Application folder.
Add this line to your .bashrc file: PATH="/Applications/CMake.app/Contents/bin":"$PATH"
Reload your .bashrc file: source ~/.bashrc
Verify the latest cmake version is installed: cmake --version
You can launch the CMake GUI by clicking on LaunchPad and typing cmake. Click on the CMake icon that appears.
The simple answer is that you can't. box-shadow applies to the whole element only. You could use a different approach and use ::before in CSS to insert an 1-pixel high element into header nav and set the box-shadow on that instead.
The PHP Obfuscator tool scrambles PHP source code to make it very difficult to understand or reverse-engineer (example). This provides significant protection for source code intellectual property that must be hosted on a website or shipped to a customer. It is a member of SD's family of Source Code Obfuscators.
For android development, to convert keystore created in eclipse ADT into public key and private key used in SignApk.jar:
export private key:
keytool.exe -importkeystore -srcstoretype JKS -srckeystore my-release-key.keystore -deststoretype PKCS12 -destkeystore keys.pk12.der
openssl.exe pkcs12 -in keys.pk12.der -nodes -out private.rsa.pem
edit private.rsa.pem and leave "-----BEGIN PRIVATE KEY-----" to "-----END PRIVATE KEY-----" paragraph, then:
openssl.exe base64 -d -in private.rsa.pem -out private.rsa.der
export public key:
keytool.exe -exportcert -keystore my-release-key.keystore -storepass <KEYSTORE_PASSWORD> -alias alias_name -file public.x509.der
sign apk:
java -jar SignApk.jar public.x509.der private.rsa.der input.apk output.apk
If you are using a navigation controller you can segue again to the current UIViewController and it will be refreshed.
Try using a format like %d.%02d
int iAmount = 10050;
printf("The number with fake decimal point is %d.%02d", iAmount/100, iAmount%100);
Another approach is to type cast it to double before printing it using %f like this:
printf("The number with fake decimal point is %0.2f", (double)(iAmount)/100);
My 2 cents :)
I try to have two pings in the same window, and it is a serial command on the same line. After finishing the first, run the second command.
The solution was to combine with start /b
on a Windows 7 command prompt.
Start as usual, without /b
, and launch in a separate window.
The command used to launch in the same line is:
start /b command1 parameters & command2 parameters
Any way, if you wish to parse the output, I don't recommend to use this. I noticed the output is scrambled between the output of the commands.
Summarizing the most relevant comments in one answer:
You have to build the regex as a string:
TEXTO = sys.argv[1]
my_regex = r"\b(?=\w)" + re.escape(TEXTO) + r"\b(?!\w)"
if re.search(my_regex, subject, re.IGNORECASE):
etc.
Note the use of re.escape
so that if your text has special characters, they won't be interpreted as such.
This should do it:
UPDATE ProductReviews
SET ProductReviews.status = '0'
FROM ProductReviews
INNER JOIN products
ON ProductReviews.pid = products.id
WHERE ProductReviews.id = '17190'
AND products.shopkeeper = '89137'
If you're iterating over an object instead of an array, you'll need to access the properties using:
$id = $blog->id;
$title = $blog->title;
$content = $blog->content;
That, or change your object to an array.
Here's another way to do it using map() and lambda functions:
>>> map(lambda d: d['value'], l)
where l is the list. I see this way "sexiest", but I would do it using the list comprehension.
Update: In case that 'value' might be missing as a key use:
>>> map(lambda d: d.get('value', 'default value'), l)
Update: I'm also not a big fan of lambdas, I prefer to name things... this is how I would do it with that in mind:
>>> import operator
>>> get_value = operator.itemgetter('value')
>>> map(get_value, l)
I would even go further and create a sole function that explicitly says what I want to achieve:
>>> import operator, functools
>>> get_value = operator.itemgetter('value')
>>> get_values = functools.partial(map, get_value)
>>> get_values(l)
... [<list of values>]
With Python 3, since map
returns an iterator, use list
to return a list, e.g. list(map(operator.itemgetter('value'), l))
.
new SecondForm().setVisible(true);
You can either use setVisible(false)
or dispose()
method to disappear current form.
SELECT CONVERT(INT, 11.4)
RESULT: 11
SELECT CONVERT(INT, 11.6)
RESULT: 11
NSString *str = (NSString *)CFURLCreateStringByAddingPercentEscapes(
NULL,
(CFStringRef)yourString,
NULL,
CFSTR("/:"),
kCFStringEncodingUTF8);
You will need to release or autorelease str
yourself.
You can use annotate your method with @Scheduled(cron ="0 1 1 * * ?")
.
0 - is for seconds
1- 1 minute
1 - hour of the day.
I came across this just now doing the same search, and found the other answers are far too specific. I also google searched for downloading android-ndk-r8
and found next to nothing. To get the correct version, I instead went here:
https://developer.android.com/ndk/downloads/index.html
And copied the link to the download I needed, and pasted it into the URL bar. There, I edited the version to reflect what I wanted (for example, I changed r8b
to r8
). Then I pressed enter, and the correct download began.
As long as the naming conventions remain the same, this should work across all versions.
Edit: This convention did change. Some older versions are now available in the archives. For even older versions, refer to the links provided by the answer above.
Another way hasn't been given yet:
try:
1/0
except Exception, e:
print e.message
Output:
integer division or modulo by zero
args[0]
might actually not be a message.
str(e)
might return the string with surrounding quotes and possibly with the leading u
if unicode:
'integer division or modulo by zero'
repr(e)
gives the full exception representation which is not probably what you want:
"ZeroDivisionError('integer division or modulo by zero',)"
edit
My bad !!! It seems that BaseException.message
has been deprecated from 2.6
, finally, it definitely seems that there is still not a standardized way to display exception messages. So I guess the best is to do deal with e.args
and str(e)
depending on your needs (and possibly e.message
if the lib you are using is relying on that mechanism).
For instance, with pygraphviz
, e.message
is the only way to display correctly the exception, using str(e)
will surround the message with u''
.
But with MySQLdb
, the proper way to retrieve the message is e.args[1]
: e.message
is empty, and str(e)
will display '(ERR_CODE, "ERR_MSG")'
You should install a editor (or IDE) supporting Python syntax. It can highlight source code and make basic format checking. For example: Eric4, Spyder, Ninjia, or Emacs, Vi.
Aside from all the answers, if you want a nice GUI tool to edit your Windows environment variables you can use Rapid Environment Editor.
Try it! It's safe to use and is awesome!
I wrote a c++ program based on Win32 to write an assembly to the boot sector of a pen-drive. When the computer is booted from the pen-drive it executes the code successfully - have a look here C++ Program to write to the boot sector of a USB Pendrive
This program is a few lines that should be compiled on a compiler with windows compilation configured - such as a visual studio compiler - any available version.
<div id="AlertDiv" style="width:600px;height:400px;border:SOLID 1px;">
<h1 style="width:100%;height:10%;text-align:center;position:relative;top:40%;">Yes</h1>
</div>
You can try the code here:
This works:
from datetime import date
today =date.today()
Output in this time: 2020-08-29
Additional:
this_year = date.today().year
this_month = date.today().month
this_day = date.today().day
print(today)
print(this_year)
print(this_month)
print(this_day)
What's wrong with using Git For Windows? From the repo view, there's an icon of the branch you're in (at the top), and if you click on manage you can drag&drop in a very visual and convenient way.
Unlike Amagrammer said, it's possible. You have to subclass your navigationController
. I explained everything here (including example code).
Your form should look like this :
<form action="myprocessingscript.php" method="POST">
<input name="field1" type="text" />
<input name="field2" type="text" />
<input type="submit" name="submit" value="Save Data">
</form>
and the PHP
<?php
if(isset($_POST['field1']) && isset($_POST['field2'])) {
$data = $_POST['field1'] . '-' . $_POST['field2'] . "\r\n";
$ret = file_put_contents('/tmp/mydata.txt', $data, FILE_APPEND | LOCK_EX);
if($ret === false) {
die('There was an error writing this file');
}
else {
echo "$ret bytes written to file";
}
}
else {
die('no post data to process');
}
I wrote to /tmp/mydata.txt
because this way I know exactly where it is. using data.txt
writes to that file in the current working directory which I know nothing of in your example.
file_put_contents
opens, writes and closes files for you. Don't mess with it.
Further reading: file_put_contents
I am using this with Beautifulsoup 4.8.1 to get the value of all class attributes of certain elements:
from bs4 import BeautifulSoup
html = "<td class='val1'/><td col='1'/><td class='val2' />"
bsoup = BeautifulSoup(html, 'html.parser')
for td in bsoup.find_all('td'):
if td.has_attr('class'):
print(td['class'][0])
Its important to note that the attribute key retrieves a list even when the attribute has only a single value.
At the top level menus, select 'Search' -> 'File Search' Then near the bottom (in the scope) there is a choice to select the entire workspace.
For your "File search has encountered a problem", you need to refresh the files in your workspace, in the Project/Package Explorer, right click and select "Refresh" at any level (project, folder, file). This will sync your workspace with the underlying file system and prevent the problem.
knowTypeList parameter let serialize with DataContractSerializer several known types:
private static void WriteObject(
string fileName, IEnumerable<Vehichle> reflectedInstances, List<Type> knownTypeList)
{
using (FileStream writer = new FileStream(fileName, FileMode.Append))
{
foreach (var item in reflectedInstances)
{
var serializer = new DataContractSerializer(typeof(Vehichle), knownTypeList);
serializer.WriteObject(writer, item);
}
}
}
for horizontaly centering you can have something like this:
.centering{
float:none;
margin:0 auto
}
<div class="span8 centering"></div>
None of them worked for me, try this one
private void scrollingWhileKeyboard() {
drawerlayout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
Rect r = new Rect();
try {
drawerlayout.getWindowVisibleDisplayFrame(r);
int screenHeight = drawerlayout.getRootView().getHeight();
int keypadHeight = screenHeight - r.bottom;
if (keypadHeight > screenHeight * 0.15) {
tabLayout.setVisibility(View.GONE);
} else {
tabLayout.setVisibility(View.VISIBLE);
}
} catch (NullPointerException e) {
}
}
});
}
Javascript for all!
String.prototype.repeat = function(num) {
if (num < 0) {
return '';
} else {
return new Array(num + 1).join(this);
}
};
function is_defined(x) {
return typeof x !== 'undefined';
}
function is_object(x) {
return Object.prototype.toString.call(x) === "[object Object]";
}
function is_array(x) {
return Object.prototype.toString.call(x) === "[object Array]";
}
/**
* Main.
*/
function xlog(v, label) {
var tab = 0;
var rt = function() {
return ' '.repeat(tab);
};
// Log Fn
var lg = function(x) {
// Limit
if (tab > 10) return '[...]';
var r = '';
if (!is_defined(x)) {
r = '[VAR: UNDEFINED]';
} else if (x === '') {
r = '[VAR: EMPTY STRING]';
} else if (is_array(x)) {
r = '[\n';
tab++;
for (var k in x) {
r += rt() + k + ' : ' + lg(x[k]) + ',\n';
}
tab--;
r += rt() + ']';
} else if (is_object(x)) {
r = '{\n';
tab++;
for (var k in x) {
r += rt() + k + ' : ' + lg(x[k]) + ',\n';
}
tab--;
r += rt() + '}';
} else {
r = x;
}
return r;
};
// Space
document.write('\n\n');
// Log
document.write('< ' + (is_defined(label) ? (label + ' ') : '') + Object.prototype.toString.call(v) + ' >\n' + lg(v));
};
// Demo //
var o = {
'aaa' : 123,
'bbb' : 'zzzz',
'o' : {
'obj1' : 'val1',
'obj2' : 'val2',
'obj3' : [1, 3, 5, 6],
'obj4' : {
'a' : 'aaaa',
'b' : null
}
},
'a' : [ 'asd', 123, false, true ],
'func' : function() {
alert('test');
},
'fff' : false,
't' : true,
'nnn' : null
};
xlog(o, 'Object'); // With label
xlog(o); // Without label
xlog(['asd', 'bbb', 123, true], 'ARRAY Title!');
var no_definido;
xlog(no_definido, 'Undefined!');
xlog(true);
xlog('', 'Empty String');
Here is example using xargs
:
$ xargs -d '\n' -I% sh -c 'echo % | wc -c' < file
For simple things, I just use the XmlDocument/XmlNode/XmlAttribute classes and XmlDocument DOM found in System.XML.
It generates the XML for me, I just need to link a few items together.
However, on larger things, I use XML serialization.
Swift 3.0
i had the same problem, i found on the documentation Apple this solution.
let numbers = [1, 2, 3, 4]
let addTwo: (Int, Int) -> Int = { x, y in x + y }
let numberSum = numbers.reduce(0, addTwo)
// 'numberSum' == 10
But, in my case i had a list of object, then i needed transform my value of my list:
let numberSum = self.list.map({$0.number_here}).reduce(0, { x, y in x + y })
this work for me.
I used to be irked by this problem; and I used to have a macro-cum-wrapper-function solution just like in Talonmies and Jared's answers, but, honestly? It makes using the CUDA Runtime API even more ugly and C-like.
So I've approached this in a different and more fundamental way. For a sample of the result, here's part of the CUDA vectorAdd
sample - with complete error checking of every runtime API call:
// (... prepare host-side buffers here ...)
auto current_device = cuda::device::current::get();
auto d_A = cuda::memory::device::make_unique<float[]>(current_device, numElements);
auto d_B = cuda::memory::device::make_unique<float[]>(current_device, numElements);
auto d_C = cuda::memory::device::make_unique<float[]>(current_device, numElements);
cuda::memory::copy(d_A.get(), h_A.get(), size);
cuda::memory::copy(d_B.get(), h_B.get(), size);
// (... prepare a launch configuration here... )
cuda::launch(vectorAdd, launch_config,
d_A.get(), d_B.get(), d_C.get(), numElements
);
cuda::memory::copy(h_C.get(), d_C.get(), size);
// (... verify results here...)
Again - all potential errors are checked , and an exception if an error occurred (caveat: If the kernel caused some error after launch, it will be caught after the attempt to copy the result, not before; to ensure the kernel was successful you would need to check for error between the launch and the copy with a cuda::outstanding_error::ensure_none()
command).
The code above uses my
Thin Modern-C++ wrappers for the CUDA Runtime API library (Github)
Note that the exceptions carry both a string explanation and the CUDA runtime API status code after the failing call.
A few links to how CUDA errors are automagically checked with these wrappers:
An array should obviously be "traversed" right-to-left to avoid unneccessary copying of values back and forth.
If you have unlimited memory, you can allocate a bit array for sizeof(type-of-element-in-array) / 8
bytes to have each bit signify whether you've already encountered corresponding value or not.
If you don't, I can't think of anything better than traversing an array and comparing each value with values that follow it and then if duplicate is found, remove these values altogether. This is somewhere near O(n^2) (or O((n^2-n)/2)).
IBM has an article on kinda close subject.
using Apache IO could be another option for copy the Stream
@RequestMapping(path = "/file/{fileId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<?> downloadFile(@PathVariable(value="fileId") String fileId,HttpServletResponse response) throws Exception {
InputStream yourInputStream = ...
IOUtils.copy(yourInputStream, response.getOutputStream());
response.flushBuffer();
return ResponseEntity.ok().build();
}
maven dependency
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-io</artifactId>
<version>1.3.2</version>
</dependency>
test open the termenal or cmd. go to the [tomcat-home]\bin directory. ex: c:\tomcat8\bin write the following command: Tomcat8W //ES//Tomcat8 will open dialog, select the java tap(top tap). change the Java virtual Machine value.
have this in index
<link rel="opengraph" href="{http://yourPage.com/subdomain.php}"/>
have this in ajaxfiles og:type"og:title"og:description and og: image
and add this also
<link rel="origin" href={http://yourPage.com}/>
then add in js after the ajaxCall
FB.XFBML.parse();
Edit: You can then display the correct title and image to facebook in txt/php douments(mine are just named .php as extensions, but are more txt files). I then have the meta tags in these files, and the link back to index in every document, also a meta link in the index file for every subfile..
if anyone knows a better way of doing this I would appreciate any additions :)
This also works in Java 8 :
Path file = Paths.get("Some path");
file = Paths.get(file + "Some other path");
this is the correct answer
$('#theid').css('display') == 'none'
You can also use following line to find if it is display block or none
$('.deal_details').is(':visible')
Nothing - Google says it clearly that the application is identified by the keys used to sign it. Consequently if you've lost the keys, you need to create a new application.
kubectl get nodes
Result:
NAME STATUS AGE
192.168.1.157 NotReady 42d
192.168.1.158 Ready 42d
192.168.1.159 Ready 42d
Here is a NotReady on the node of 192.168.1.157
. Then debugging this notready node, and you can read offical documents - Application Introspection and Debugging.
kubectl describe node 192.168.1.157
Partial Result:
Conditions:
Type Status LastHeartbeatTime LastTransitionTime Reason Message
---- ------ ----------------- ------------------ ------ -------
OutOfDisk Unknown Sat, 28 Dec 2016 12:56:01 +0000 Sat, 28 Dec 2016 12:56:41 +0000 NodeStatusUnknown Kubelet stopped posting node status.
Ready Unknown Sat, 28 Dec 2016 12:56:01 +0000 Sat, 28 Dec 2016 12:56:41 +0000 NodeStatusUnknown Kubelet stopped posting node status.
There is a OutOfDisk on my node, then Kubelet stopped posting node status.
So, I must free some disk space, using the command of df
on my Ubuntu14.04 I can check the details of memory, and using the command of docker rmi image_id/image_name
under the role of su
I can remove the useless images.
Login in 192.168.1.157
by using ssh, like ssh [email protected]
, and switch to the 'su' by sudo su
;
/etc/init.d/kubelet restart
Result:
stop: Unknown instance:
kubelet start/running, process 59261
On the master:
kubectl get nodes
Result:
NAME STATUS AGE
192.168.1.157 Ready 42d
192.168.1.158 Ready 42d
192.168.1.159 Ready 42d
Ok, that node works fine.
Here is a reference: Kubernetes
Do you have a smart phone? Is there one big app or lots of little ones? Does one app reply upon another? Can you use one app while installing, updating, and/or uninstalling another? That each app is self-contained is high cohesion. That each app is independent of the others is low coupling. DevOps favours this architecture because it means you can do discrete continuous deployment without disrupting the system entire.
With the introduction of f-strings in Python 3.6, this will also work:
f'{10}' == '10'
It is actually faster than calling str()
, at the cost of readability.
In fact, it's faster than %x
string formatting and .format()
!
This is a mistake:
m.check(side);
That code has to go inside a function. Your class definition can only contain declarations and functions.
Classes don't "run", they provide a blueprint for how to make an object.
The line Message m;
means that an Orderbook
will contain Message
called m
, if you later create an Orderbook
.
You can use the pandas.DataFrame.quantile() function, as shown below.
import pandas as pd
import random
A = [ random.randint(0,100) for i in range(10) ]
B = [ random.randint(0,100) for i in range(10) ]
df = pd.DataFrame({ 'field_A': A, 'field_B': B })
df
# field_A field_B
# 0 90 72
# 1 63 84
# 2 11 74
# 3 61 66
# 4 78 80
# 5 67 75
# 6 89 47
# 7 12 22
# 8 43 5
# 9 30 64
df.field_A.mean() # Same as df['field_A'].mean()
# 54.399999999999999
df.field_A.median()
# 62.0
# You can call `quantile(i)` to get the i'th quantile,
# where `i` should be a fractional number.
df.field_A.quantile(0.1) # 10th percentile
# 11.9
df.field_A.quantile(0.5) # same as median
# 62.0
df.field_A.quantile(0.9) # 90th percentile
# 89.10000000000001
In /etc/ansible/ansible.cfg
uncomment the line:
host_key_check = False
and in /etc/ansible/hosts
uncomment the line
client_ansible ansible_ssh_host=10.1.1.1 ansible_ssh_user=root ansible_ssh_pass=12345678
That's all
For anyone else that comes across this post and might find it useful... There is actually nothing wrong with my code. I made the mistake of requesting client_credentials type access code instead of password access code (#facepalms). FYI I am using urlencoded post hence the use of querystring.. So for those that may be looking for some example code.. here is my full request
Big thanks to @swapnil for trying to help me debug this.
const data = {
grant_type: USER_GRANT_TYPE,
client_id: CLIENT_ID,
client_secret: CLIENT_SECRET,
scope: SCOPE_INT,
username: DEMO_EMAIL,
password: DEMO_PASSWORD
};
axios.post(TOKEN_URL, Querystring.stringify(data))
.then(response => {
console.log(response.data);
USER_TOKEN = response.data.access_token;
console.log('userresponse ' + response.data.access_token);
})
.catch((error) => {
console.log('error ' + error);
});
const AuthStr = 'Bearer '.concat(USER_TOKEN);
axios.get(URL, { headers: { Authorization: AuthStr } })
.then(response => {
// If request is good...
console.log(response.data);
})
.catch((error) => {
console.log('error ' + error);
});
I'm just sharing this answer because I had similar problem.
In the end, error was caused because I inadvertently changed the fileTree
. In my case, I fixed by changing:
// implementation or compile
implementation fileTree(include: ['*.jar'])
to
// implementation or compile
implementation fileTree(include: ['*.jar'], dir: 'libs')
In order to find the day after one month, it is necessary to look at what day of the month it is today.
So if the day is first day of month run following code
Calendar calendar = Calendar.getInstance();
Calendar calFebruary = Calendar.getInstance();
calFebruary.set(Calendar.MONTH, Calendar.FEBRUARY);
if (calendar.get(Calendar.DAY_OF_MONTH) == 1) {// if first day of month
calendar.add(Calendar.MONTH, 1);
calendar.set(Calendar.DATE, calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
Date nextMonthFirstDay = calendar.getTime();
System.out.println(nextMonthFirstDay);
}
if the day is last day of month, run following codes.
else if ((calendar.getActualMaximum(Calendar.DAY_OF_MONTH) == calendar.get(Calendar.DAY_OF_MONTH))) {// if last day of month
calendar.add(Calendar.MONTH, 1);
calendar.set(Calendar.DATE, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
Date nextMonthLastDay = calendar.getTime();
System.out.println(nextMonthLastDay);
}
if the day is in february run following code
else if (calendar.get(Calendar.MONTH) == Calendar.JANUARY
&& calendar.get(Calendar.DAY_OF_MONTH) > calFebruary.getActualMaximum(Calendar.DAY_OF_MONTH)) {// control of february
calendar.add(Calendar.MONTH, 1);
calendar.set(Calendar.DATE, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
Date nextMonthLastDay = calendar.getTime();
System.out.println(nextMonthLastDay);
}
the following codes are used for other cases.
else { // any day
calendar.add(Calendar.DATE, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
Date theNextDate = calendar.getTime();
System.out.println(theNextDate);
}
Basically in this case, System.Data.OracleClient need access to some of the oracle dll which are not part of .Net. Solutions:
I find that typically:
So @mark-keen's answer works well but having an interface provides more flexibility:
public static class MyViewHolder extends RecyclerView.ViewHolder {
public ImageView iconImageView;
public TextView iconTextView;
public MyViewHolder(final View itemView) {
super(itemView);
iconImageView = (ImageView) itemView.findViewById(R.id.myRecyclerImageView);
iconTextView = (TextView) itemView.findViewById(R.id.myRecyclerTextView);
iconTextView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onClickListener.iconTextViewOnClick(v, getAdapterPosition());
}
});
iconImageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onClickListener.iconImageViewOnClick(v, getAdapterPosition());
}
});
}
}
Where onClickListener is defined in your adapter:
public MyAdapterListener onClickListener;
public interface MyAdapterListener {
void iconTextViewOnClick(View v, int position);
void iconImageViewOnClick(View v, int position);
}
And probably set through your constructor:
public MyAdapter(ArrayList<MyListItems> newRows, MyAdapterListener listener) {
rows = newRows;
onClickListener = listener;
}
Then you can handle the events in your Activity or wherever your RecyclerView is being used:
mAdapter = new MyAdapter(mRows, new MyAdapter.MyAdapterListener() {
@Override
public void iconTextViewOnClick(View v, int position) {
Log.d(TAG, "iconTextViewOnClick at position "+position);
}
@Override
public void iconImageViewOnClick(View v, int position) {
Log.d(TAG, "iconImageViewOnClick at position "+position);
}
});
mRecycler.setAdapter(mAdapter);
This is a base service class (ServiceBase subclass) that can be subclassed to build a windows service that can be easily installed from the command line, without installutil.exe. This solution is derived from How to make a .NET Windows Service start right after the installation?, adding some code to get the service Type using the calling StackFrame
public abstract class InstallableServiceBase:ServiceBase
{
/// <summary>
/// returns Type of the calling service (subclass of InstallableServiceBase)
/// </summary>
/// <returns></returns>
protected static Type getMyType()
{
Type t = typeof(InstallableServiceBase);
MethodBase ret = MethodBase.GetCurrentMethod();
Type retType = null;
try
{
StackFrame[] frames = new StackTrace().GetFrames();
foreach (StackFrame x in frames)
{
ret = x.GetMethod();
Type t1 = ret.DeclaringType;
if (t1 != null && !t1.Equals(t) && !t1.IsSubclassOf(t))
{
break;
}
retType = t1;
}
}
catch
{
}
return retType;
}
/// <summary>
/// returns AssemblyInstaller for the calling service (subclass of InstallableServiceBase)
/// </summary>
/// <returns></returns>
protected static AssemblyInstaller GetInstaller()
{
Type t = getMyType();
AssemblyInstaller installer = new AssemblyInstaller(
t.Assembly, null);
installer.UseNewContext = true;
return installer;
}
private bool IsInstalled()
{
using (ServiceController controller =
new ServiceController(this.ServiceName))
{
try
{
ServiceControllerStatus status = controller.Status;
}
catch
{
return false;
}
return true;
}
}
private bool IsRunning()
{
using (ServiceController controller =
new ServiceController(this.ServiceName))
{
if (!this.IsInstalled()) return false;
return (controller.Status == ServiceControllerStatus.Running);
}
}
/// <summary>
/// protected method to be called by a public method within the real service
/// ie: in the real service
/// new internal void InstallService()
/// {
/// base.InstallService();
/// }
/// </summary>
protected void InstallService()
{
if (this.IsInstalled()) return;
try
{
using (AssemblyInstaller installer = GetInstaller())
{
IDictionary state = new Hashtable();
try
{
installer.Install(state);
installer.Commit(state);
}
catch
{
try
{
installer.Rollback(state);
}
catch { }
throw;
}
}
}
catch
{
throw;
}
}
/// <summary>
/// protected method to be called by a public method within the real service
/// ie: in the real service
/// new internal void UninstallService()
/// {
/// base.UninstallService();
/// }
/// </summary>
protected void UninstallService()
{
if (!this.IsInstalled()) return;
if (this.IsRunning()) {
this.StopService();
}
try
{
using (AssemblyInstaller installer = GetInstaller())
{
IDictionary state = new Hashtable();
try
{
installer.Uninstall(state);
}
catch
{
throw;
}
}
}
catch
{
throw;
}
}
private void StartService()
{
if (!this.IsInstalled()) return;
using (ServiceController controller =
new ServiceController(this.ServiceName))
{
try
{
if (controller.Status != ServiceControllerStatus.Running)
{
controller.Start();
controller.WaitForStatus(ServiceControllerStatus.Running,
TimeSpan.FromSeconds(10));
}
}
catch
{
throw;
}
}
}
private void StopService()
{
if (!this.IsInstalled()) return;
using (ServiceController controller =
new ServiceController(this.ServiceName))
{
try
{
if (controller.Status != ServiceControllerStatus.Stopped)
{
controller.Stop();
controller.WaitForStatus(ServiceControllerStatus.Stopped,
TimeSpan.FromSeconds(10));
}
}
catch
{
throw;
}
}
}
}
All you have to do is to implement two public/internal methods in your real service:
new internal void InstallService()
{
base.InstallService();
}
new internal void UninstallService()
{
base.UninstallService();
}
and then call them when you want to install the service:
static void Main(string[] args)
{
if (Environment.UserInteractive)
{
MyService s1 = new MyService();
if (args.Length == 1)
{
switch (args[0])
{
case "-install":
s1.InstallService();
break;
case "-uninstall":
s1.UninstallService();
break;
default:
throw new NotImplementedException();
}
}
}
else {
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new MyService()
};
ServiceBase.Run(MyService);
}
}
The problem with camel case is that there are often different interpretations of words - for example, checkinService vs checkInService. Going along with Aaron's answer, it is difficult with auto-completion if you have many similarly named repos to have to constantly check if the person who created the repo you care about used a certain breakdown of the upper and lower cases. avoid upper case.
His point about dashes is also well-advised.
You can do so by extending jQuerys functionality. This will shorten the amount of text you have to write for the selector.
$.extend($.expr[':'], {
unchecked: function (obj) {
return ((obj.type == 'checkbox' || obj.type == 'radio') && !$(obj).is(':checked'));
}
}
);
You can then use $("input:unchecked")
to get all checkboxes and radio buttons that are checked.
/// get set value field in object to object new (two object field like )
public static void SetValueObjectToObject (object sourceObj , object resultObj)
{
IList<PropertyInfo> props = new List<PropertyInfo>(sourceObj.GetType().GetProperties());
foreach (PropertyInfo prop in props)
{
try
{
//get value in sourceObj
object propValue = prop.GetValue(sourceObj, null);
//set value in resultObj
PropertyInfo propResult = resultObj.GetType().GetProperty(prop.Name, BindingFlags.Public | BindingFlags.Instance);
if (propResult != null && propResult.CanWrite)
{
propResult.SetValue(resultObj, propValue, null);
}
}
catch (Exception ex)
{
// do something with Ex
}
}
}
TextView textView = (TextView)mySpinner.getSelectedView();
String result = textView.getText().toString();
HTML
<form method="post">
<textarea name="postes" id="textAreaPost" placeholder="Write what's you new" maxlength="500"></textarea>
<div id="char_namb" style="padding: 4px; float: right; font-size: 20px; font-family: Cocon; text-align: center;">500 : 0</div>
</form>
jQuery
$(function(){
$('#textAreaPost').keyup(function(){
var charsno = $(this).val().length;
$('#char_namb').html("500 : " + charsno);
});
});
In case of changing all the keys at once. Here I am stemming the keys.
a = {'making' : 1, 'jumping' : 2, 'climbing' : 1, 'running' : 2}
b = {ps.stem(w) : a[w] for w in a.keys()}
print(b)
>>> {'climb': 1, 'jump': 2, 'make': 1, 'run': 2} #output
using (StreamWriter writer = File.AppendText(LoggingPath))
{
writer.WriteLine("Text");
}
You need to enter the width % for each cell. But wait, there's a better way to do that, it's called CSS:
<style>
.equalDivide tr td { width:25%; }
</style>
<table class="equalDivide" cellpadding="0" cellspacing="0" width="100%" border="0">
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</table>
I agree with @Brian Clapper. I have used SuperCSV as a parser though I've had mixed results. I enjoy the versatility of it, but there are some situations within my own csv files for which I have not been able to reconcile "yet". I have faith in this product and would recommend it overall--I'm just missing something simple, no doubt, that I'm doing in my own implementation.
SuperCSV can parse the columns into various formats, do edits on the columns, etc. It's worth taking a look-see. It has examples as well, and easy to follow.
The one/only limitation I'm having is catching an 'empty' column and parsing it into an Integer or maybe a blank, etc. I'm getting null-pointer errors, but javadocs suggest each cellProcessor checks for nulls first. So, I'm blaming myself first, for now. :-)
Anyway, take a look at SuperCSV. http://supercsv.sourceforge.net/
Fetch does not use cookie by default. To enable cookie, do this:
fetch(url, {
credentials: "same-origin"
}).then(...).catch(...);
Well the most used pattern for reusable logic I have come across is either writing a hook or creating a utils file. It depends on what you want to accomplish.
hooks/useForm.js
Like if you want to validate form data then I would create a custom hook named useForm.js and provide it form data and in return it would return me an object containing two things:
Object: {
value,
error,
}
You can definitely return more things from it as you progress.
utils/URL.js
Another example would be like you want to extract some information from a URL then I would create a utils file for it containing a function and import it where needed:
export function getURLParam(p) {
...
}
when your document is ready that doesn't mean that your iframe is ready too,
so you should listen to the iframe load event then access your contents:
$(function() {
$("#my-iframe").bind("load",function(){
$(this).contents().find("[tokenid=" + token + "]").html();
});
});
As promised, I'm putting an example for how to use annotations to serialize/deserialize polymorphic objects, I based this example in the Animal
class from the tutorial you were reading.
First of all your Animal
class with the Json Annotations for the subclasses.
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY)
@JsonSubTypes({
@JsonSubTypes.Type(value = Dog.class, name = "Dog"),
@JsonSubTypes.Type(value = Cat.class, name = "Cat") }
)
public abstract class Animal {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Then your subclasses, Dog
and Cat
.
public class Dog extends Animal {
private String breed;
public Dog() {
}
public Dog(String name, String breed) {
setName(name);
setBreed(breed);
}
public String getBreed() {
return breed;
}
public void setBreed(String breed) {
this.breed = breed;
}
}
public class Cat extends Animal {
public String getFavoriteToy() {
return favoriteToy;
}
public Cat() {}
public Cat(String name, String favoriteToy) {
setName(name);
setFavoriteToy(favoriteToy);
}
public void setFavoriteToy(String favoriteToy) {
this.favoriteToy = favoriteToy;
}
private String favoriteToy;
}
As you can see, there is nothing special for Cat
and Dog
, the only one that know about them is the abstract
class Animal
, so when deserializing, you'll target to Animal
and the ObjectMapper
will return the actual instance as you can see in the following test:
public class Test {
public static void main(String[] args) {
ObjectMapper objectMapper = new ObjectMapper();
Animal myDog = new Dog("ruffus","english shepherd");
Animal myCat = new Cat("goya", "mice");
try {
String dogJson = objectMapper.writeValueAsString(myDog);
System.out.println(dogJson);
Animal deserializedDog = objectMapper.readValue(dogJson, Animal.class);
System.out.println("Deserialized dogJson Class: " + deserializedDog.getClass().getSimpleName());
String catJson = objectMapper.writeValueAsString(myCat);
Animal deseriliazedCat = objectMapper.readValue(catJson, Animal.class);
System.out.println("Deserialized catJson Class: " + deseriliazedCat.getClass().getSimpleName());
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output after running the Test
class:
{"@type":"Dog","name":"ruffus","breed":"english shepherd"}
Deserialized dogJson Class: Dog
{"@type":"Cat","name":"goya","favoriteToy":"mice"}
Deserialized catJson Class: Cat
Hope this helps,
Jose Luis
You are setting the label text before the button is clicked to "txt". Instead when the button is clicked call setText()
on the label and pass it the text from the text field.
Example:
label1.setText(nameField.getText());
It's not "plumbing", but it'll do exactly what you want:
$ git log --format=%B -n 1 <commit>
If you absolutely need a "plumbing" command (not sure why that's a requirement), you can use rev-list
:
$ git rev-list --format=%B --max-count=1 <commit>
Although rev-list
will also print out the commit sha (on the first line) in addition to the commit message.
I tried everything I could find but nothing worked. Then I highlighted the formula column and right-clicked and selected 'clear contents'. That worked! Now I see the results, not the formula.
In your button1_click function you are using '==' for button2.Enabled == true;
This should be button2.Enabled = true;
Worked for me in 30 seconds, short and sweet:
Found this: https://coderwall.com/p/ngisma where Nathan Walker (near bottom of page) suggests a decorator in $rootScope to create func 'safeApply', code:
yourAwesomeModule.config([
'$provide', function($provide) {
return $provide.decorator('$rootScope', [
'$delegate', function($delegate) {
$delegate.safeApply = function(fn) {
var phase = $delegate.$$phase;
if (phase === "$apply" || phase === "$digest") {
if (fn && typeof fn === 'function') {
fn();
}
} else {
$delegate.$apply(fn);
}
};
return $delegate;
}
]);
}
]);
are you using jquery and prototype on the same page by any chance?
If so, use jquery noConflict mode, otherwise you are overwriting prototypes $ function.
noConflict mode is activated by doing the following:
<script src="jquery.js"></script>
<script>jQuery.noConflict();</script>
Note: by doing this, the dollar sign variable no longer represents the jQuery object. To keep from rewriting all your jQuery code, you can use this little trick to create a dollar sign scope for jQuery:
jQuery(function ($) {
// The dollar sign will equal jQuery in this scope
});
// Out here, the dollar sign still equals Prototype
I had some git submodule misconfiguration. I went to repo's root and issued these commands on the directories that had .git
folders previously:
git rm --cached sub/directory/path -f
Then the directories appeared in git status
.
You may want to make a copy of your repo before trying this just in case.
IaaS, PaaS and SaaS are basically cloud computing segment.
IaaS (Infrastructure as a Service) - Infrastructure as a Service is a provision model of cloud computing in which an organization outsources the equipment used to support operations, including storage, hardware, servers and networking components. The service provider owns the equipment and is responsible for housing, running and maintaining it. The client typically pays on a per-use basis. Ex- Amazon Web Services, BlueLock, Cloudscaling and Datapipe
PaaS (Platform as a Service) - Platform as a Service is one of the GROWING sector of cloud computing. PaaS basically help developer to speed the development of app, saving money and most important innovating their applications and business instead of setting up configurations and managing things like servers and databases. In one line I can say Platform as a service (PaaS) automates the configuration, deployment and ongoing management of applications in the cloud. Ex: Heroku, EngineYard, App42 PaaS and OpenShift
SaaS (Software as a Service) - Software as a Service, SaaS is a software delivery method that provides access to software and its functions remotely as a Web-based service. Ex: Abiquo's and Akamai
Use queue.rear+1
to get the length of the queue
In batch files, as in standard C programs, argument 0 contains the path to the currently executing script. You can use %~dp0
to get only the path portion of the 0th argument (which is the current script) - this path is always a fully qualified path.
You can also get the fully qualified path of your first argument by using %~f1
, but this gives a path according to the current working directory, which is obviously not what you want.
Personally, I often use the %~dp0%~1
idiom in my batch file, which interpret the first argument relative to the path of the executing batch. It does have a shortcoming though: it miserably fails if the first argument is fully-qualified.
If you need to support both relative and absolute paths, you can make use of Frédéric Ménez's solution: temporarily change the current working directory.
Here's an example that'll demonstrate each of these techniques:
@echo off
echo %%~dp0 is "%~dp0"
echo %%0 is "%0"
echo %%~dpnx0 is "%~dpnx0"
echo %%~f1 is "%~f1"
echo %%~dp0%%~1 is "%~dp0%~1"
rem Temporarily change the current working directory, to retrieve a full path
rem to the first parameter
pushd .
cd %~dp0
echo batch-relative %%~f1 is "%~f1"
popd
If you save this as c:\temp\example.bat and the run it from c:\Users\Public as
c:\Users\Public>\temp\example.bat ..\windows
...you'll observe the following output:
%~dp0 is "C:\temp\"
%0 is "\temp\example.bat"
%~dpnx0 is "C:\temp\example.bat"
%~f1 is "C:\Users\windows"
%~dp0%~1 is "C:\temp\..\windows"
batch-relative %~f1 is "C:\Windows"
the documentation for the set of modifiers allowed on a batch argument can be found here: https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/call
IIRC, something like:
set tabstop=2 shiftwidth=2 expandtab
should do the trick. If you already have tabs, then follow it up with a nice global RE to replace them with double spaces.
If you already have tabs you want to replace,
:retab
Try this instead of your code:
var type=$("#the-span").attr("data-type");
alert(type);
A hacky way of doing JSON_UNESCAPED_UNICODE in PHP 5.3. Really disappointed by PHP json support. Maybe this will help someone else.
$array = some_json();
// Encode all string children in the array to html entities.
array_walk_recursive($array, function(&$item, $key) {
if(is_string($item)) {
$item = htmlentities($item);
}
});
$json = json_encode($array);
// Decode the html entities and end up with unicode again.
$json = html_entity_decode($rson);
When you get this error some annotation is missing. I was missing @service annotation on service. When I added that annotation it worked fine for me.
(see detailed explanation here)
$text = Get-Content $filePath | Out-String
The IO.File.ReadAllText
didn't work for me with a relative path, it looks for the file in %USERPROFILE%\$filePath
instead of the current directory (when running from Powershell ISE at least):
$text = [IO.File]::ReadAllText($filePath)
$text = Get-Content $filePath -Raw
You can run javascript code at any time. AFAIK it is executed at the moment the browser reaches the <script> tag where it is in. But you cannot access elements that are not loaded yet.
So if you need access to elements, you should wait until the DOM is loaded (this does not mean the whole page is loaded, including images and stuff. It's only the structure of the document, which is loaded much earlier, so you usually won't notice a delay), using the DOMContentLoaded
event or functions like $.ready
in jQuery.
As far as CSS styling is concerned the <button type="submit" class="Btn">Example</button>
is better as it gives you the ability to use CSS :before
and :after
pseudo classes which can help.
Due to the <input type="button">
visually rendering different to an <a>
or <span>
when styled with classes in certain situations I avoid them.
It's very worth noting the current top answer was written in 2009. IE6 isn't a concern now days so <button type="submit">Wins</button>
styling consistency in my eyes comes out on top.
In VS2013 F4 on your project to view properties window and disable Anonymous access and enable "Windows authentication"
Then it will work. No need to change anything else
UPDATE Sept 2015
This answer continues to get upvotes, so I'm going to leave it here since it seems to be helpful to some people, but please check out the other answers from @reexmonkey and @Pressacco first. They may provide better results.
ORIGINAL ANSWER
Give this a shot:
That should cause those messages to disappear.
I saved my web.xsd in the root of my web folder (which might not be the best place for it, but just for demonstration purposes) and my Schemas property looks like this:
"C:\Program Files (x86)\Microsoft Visual Studio 10.0\xml\Schemas\DotNetConfig.xsd" "Web.xsd"
I do not know whether this is the general opinion, but I've always differentiated the two by what they are used for. An emulator is used if you actually want to use the emulated machine for its output. A simulator, on the other hand, is for when you want to study the simulated machine or test its behaviour.
For example, if you want to write some state machine logic in your application (which is running on a general purpose CPU), you write a small state machine emulator. If you want to study the efficiency or viability of a state machine for a particular problem, you write a simulator.
There is no way to display interactive elements on the lockscreen or wallpaper with a non jailbroken iPhone.
I would recommend Countdown Widget it's free an you can display countdowns in the notification center which you can also access from your lockscreen.
It means "not equal to" (as in, the values in cells E37-N37 are not equal to ""
, or in other words, they are not empty.)
I use XAMPP and had the same error. I used Paul Gobée solution above and it worked for me. I navigated to C:\xampp\mysql\bin\mysqld-debug.exe
and upon starting the .exe
my Windows Firewall popped up asking for permission. Once I allowed it, it worked fine. I would have commented under his post but I do not have that much rep yet... sry! Just wanted to let everyone know this worked for me as well.
From Apple documentations:
The presenting view controller is responsible for dismissing the view controller it presented
Thus, it is a bad practise to just invoke the dismiss method from it self.
What you should do if you're presenting it modal is:
presentingViewController?.dismiss(animated: true, completion: nil)
The response by @Miknash and @wolfgang gutierrez barrera was helpful to me. Only difference was I had to add rgbValue:
to the function call.
UIColorFromHex(rgbValue: 0xA6D632,alpha: 1 )
like so
You can execute your task in a different thread. threading.Timer
will let you execute a given callback once after some time has elapsed, if you want to execute your task, for example, as long as the callback returns True
(this is actually what glib.timeout_add
provides, but you might not have it installed in windows) or until you cancel it, you can use this code:
import logging, threading, functools
import time
logging.basicConfig(level=logging.NOTSET,
format='%(threadName)s %(message)s')
class PeriodicTimer(object):
def __init__(self, interval, callback):
self.interval = interval
@functools.wraps(callback)
def wrapper(*args, **kwargs):
result = callback(*args, **kwargs)
if result:
self.thread = threading.Timer(self.interval,
self.callback)
self.thread.start()
self.callback = wrapper
def start(self):
self.thread = threading.Timer(self.interval, self.callback)
self.thread.start()
def cancel(self):
self.thread.cancel()
def foo():
logging.info('Doing some work...')
return True
timer = PeriodicTimer(1, foo)
timer.start()
for i in range(2):
time.sleep(2)
logging.info('Doing some other work...')
timer.cancel()
Example output:
Thread-1 Doing some work...
Thread-2 Doing some work...
MainThread Doing some other work...
Thread-3 Doing some work...
Thread-4 Doing some work...
MainThread Doing some other work...
Note: The callback isn't executed every interval execution. Interval is the time the thread waits between the callback finished the last time and the next time is called.
This worked for me :
<ProgressBar
android:indeterminateTint="#d60909"
... />
C++11 Thread safe implementation:
#include <iostream>
#include <thread>
class Singleton
{
private:
static Singleton * _instance;
static std::mutex mutex_;
protected:
Singleton(const std::string value): value_(value)
{
}
~Singleton() {}
std::string value_;
public:
/**
* Singletons should not be cloneable.
*/
Singleton(Singleton &other) = delete;
/**
* Singletons should not be assignable.
*/
void operator=(const Singleton &) = delete;
//static Singleton *GetInstance(const std::string& value);
static Singleton *GetInstance(const std::string& value)
{
if (_instance == nullptr)
{
std::lock_guard<std::mutex> lock(mutex_);
if (_instance == nullptr)
{
_instance = new Singleton(value);
}
}
return _instance;
}
std::string value() const{
return value_;
}
};
/**
* Static methods should be defined outside the class.
*/
Singleton* Singleton::_instance = nullptr;
std::mutex Singleton::mutex_;
void ThreadFoo(){
std::this_thread::sleep_for(std::chrono::milliseconds(10));
Singleton* singleton = Singleton::GetInstance("FOO");
std::cout << singleton->value() << "\n";
}
void ThreadBar(){
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
Singleton* singleton = Singleton::GetInstance("BAR");
std::cout << singleton->value() << "\n";
}
int main()
{
std::cout <<"If you see the same value, then singleton was reused (yay!\n" <<
"If you see different values, then 2 singletons were created (booo!!)\n\n" <<
"RESULT:\n";
std::thread t1(ThreadFoo);
std::thread t2(ThreadBar);
t1.join();
t2.join();
std::cout << "Complete!" << std::endl;
return 0;
}
Visual Studio 2013: Yes to both adding to the watch windows during debugging and dragging variables or typing them in without "user::". But before any of that would work I also needed to go to Tools > Options, then Debugging > General and had to scroll right down to the bottom of the right hand pane to be able to tick "Use Managed Compatibility Mode". Then I had to stop and restart debugging. Finally the above advice worked. Many thanks to the above and to this article: Visual Studio 2015 Debugging: Can't expand local variables?
Changing the distribution of any function to another involves using the inverse of the function you want.
In other words, if you aim for a specific probability function p(x) you get the distribution by integrating over it -> d(x) = integral(p(x)) and use its inverse: Inv(d(x)). Now use the random probability function (which have uniform distribution) and cast the result value through the function Inv(d(x)). You should get random values cast with distribution according to the function you chose.
This is the generic math approach - by using it you can now choose any probability or distribution function you have as long as it have inverse or good inverse approximation.
Hope this helped and thanks for the small remark about using the distribution and not the probability itself.
I would say that it depends of fact what do you planed to achieve with Javascript code:
Do you mean search and replace a string in all files matched by grep?
perl -p -i -e 's/oldstring/newstring/g' `grep -ril searchpattern *`
Edit
Since this seems to be a fairly popular question thought I'd update.
Nowadays I mostly use ack-grep
as it's more user-friendly. So the above command would be:
perl -p -i -e 's/old/new/g' `ack -l searchpattern`
To handle whitespace in file names you can run:
ack --print0 -l searchpattern | xargs -0 perl -p -i -e 's/old/new/g'
you can do more with ack-grep
. Say you want to restrict the search to HTML files only:
ack --print0 --html -l searchpattern | xargs -0 perl -p -i -e 's/old/new/g'
And if white space is not an issue it's even shorter:
perl -p -i -e 's/old/new/g' `ack -l --html searchpattern`
perl -p -i -e 's/old/new/g' `ack -f --html` # will match all html files
Just like to contribute that the above answers of :not() can be very effective in angular forms, rather than creating effects or adjusting the view/DOM,
input.ng-invalid:not(.ng-pristine) { ... your css here i.e. border-color: red; ...}
Ensures that on loading your page, the input fields will only show the invalid (red borders or backgrounds, etc) if they have data added (i.e. no longer pristine) but are invalid.
If you meant just ABC as simple value, answer above is the one that works fine.
If you meant concatenation of values of rows that are not selected by your main query, you will need to use a subquery.
Something like this may work:
SELECT t1.col1,
t1.col2,
(SELECT GROUP_CONCAT(col2 SEPARATOR '') FROM Table1 t2 WHERE t2.col1 != 0) as col3
FROM Table1 t1
WHERE t1.col1 = 0;
Actual syntax maybe a bit off though
UltraID3Lib...
Be aware that UltraID3Lib is no longer officially available, and thus no longer maintained. See comments below for the link to a Github project that includes this library
//using HundredMilesSoftware.UltraID3Lib;
UltraID3 u = new UltraID3();
u.Read(@"C:\mp3\song.mp3");
//view
Console.WriteLine(u.Artist);
//edit
u.Artist = "New Artist";
u.Write();
This is the simple solution. This works for me.You can use the javascript print concept and simple save this as pdf.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$("#btnPrint").live("click", function () {
var divContents = $("#dvContainer").html();
var printWindow = window.open('', '', 'height=400,width=800');
printWindow.document.write('<html><head><title>DIV Contents</title>');
printWindow.document.write('</head><body >');
printWindow.document.write(divContents);
printWindow.document.write('</body></html>');
printWindow.document.close();
printWindow.print();
});
</script>
</head>
<body>
<form id="form1">
<div id="dvContainer">
This content needs to be printed.
</div>
<input type="button" value="Print Div Contents" id="btnPrint" />
</form>
</body>
</html>
If you have a library and you want to append the log4j:
(I have assumed that you have the log4j library added.)
PD: Sorry for my english.
Combine JS & CSS :
button{
/* 1st state */
}
button:hover{
/* hover state */
}
button:active{
/* click state */
}
button.active{
/* after click state */
}
jQuery('button').click(function(){
jQuery(this).toggleClass('active');
});
Note that Git 2.5 (Q2 2015) a future Git might try to make that scenario impossible.
See commit ed178ef by Jeff King (peff
), 22 Apr 2015.
(Merged by Junio C Hamano -- gitster
-- in commit 05c3967, 19 May 2015)
Note: This has been reverted. See below.
stash
: require a clean index to apply/pop
If you have staged contents in your index and run "
stash apply/pop
", we may hit a conflict and put new entries into the index.
Recovering to your original state is difficult at that point, because tools like "git reset --keep" will blow away anything staged.
In other words:
"
git stash pop/apply
" forgot to make sure that not just the working tree is clean but also the index is clean.
The latter is important as a stash application can conflict and the index will be used for conflict resolution.
We can make this safer by refusing to apply when there are staged changes.
That means if there were merges before because of applying a stash on modified files (added but not committed), now they would not be any merges because the stash apply/pop would stop immediately with:
Cannot apply stash: Your index contains uncommitted changes.
Forcing you to commit the changes means that, in case of merges, you can easily restore the initial state( before
git stash apply/pop
) with agit reset --hard
.
See commit 1937610 (15 Jun 2015), and commit ed178ef (22 Apr 2015) by Jeff King (peff
).
(Merged by Junio C Hamano -- gitster
-- in commit bfb539b, 24 Jun 2015)
That commit was an attempt to improve the safety of applying a stash, because the application process may create conflicted index entries, after which it is hard to restore the original index state.
Unfortunately, this hurts some common workflows around "
git stash -k
", like:
git add -p ;# (1) stage set of proposed changes
git stash -k ;# (2) get rid of everything else
make test ;# (3) make sure proposal is reasonable
git stash apply ;# (4) restore original working tree
If you "git commit" between steps (3) and (4), then this just works. However, if these steps are part of a pre-commit hook, you don't have that opportunity (you have to restore the original state regardless of whether the tests passed or failed).
PHP will let you build the pages of your site that make up your video conferencing and chat applications, but it won't deliver or stream video for you - PHP runs on the server only and renders out HTML to a client browser.
For the video, the first thing you'll need is a live streaming account with someone like akamai or the numerous others in the field. Using this account gives you an ingress point for your video - ie: the server that you will stream your live video up to.
Next, you want to get your video out to the browsers - windows media player, flash or silverlight will let you achieve this - embedding the appropriate control for your chosen technology into your page (using PHP or whatever) and given the address of your live video feed.
PHP (or other scripting language) would be used to build the chat part of the application and bring the whole thing together (the chat and the embedded video player).
Hope this helps.
Come on guys, there is no need to loop, just use simple math to solve this equation system:
a*b = i;
a+b = j;
a = j/b;
a = i-b;
j/b = i-b; so:
b + j/b + i = 0
b^2 + i*b + j = 0
From here, its a quadratic equation, and it's trivial to find b (just implement the quadratic equation formula) and from there get the value for a.
EDIT:
There you go:
function finder($add,$product)
{
$inside_root = $add*$add - 4*$product;
if($inside_root >=0)
{
$b = ($add + sqrt($inside_root))/2;
$a = $add - $b;
echo "$a+$b = $add and $a*$b=$product\n";
}else
{
echo "No real solution\n";
}
}
Real live action:
sudo perl -MCPAN -e 'install Foo'
You will also get the same error ERROR 1114 (HY000): The table '#sql-310a_8867d7f' is full
if you try to add an index to a table that is using the storage engine MEMORY.
When the UI component that registers the BR is destroyed, so is the BR. Therefore when the code gets to unregistering, the BR may have already been destroyed.
Your Test2
class is not a Component
, it has a Component
which is a difference.
Either you do something like
frame.add(test.getPanel() );
after you introduced a getter for the panel in your class, or you make sure your Test2
class becomes a Component
(e.g. by extending a JPanel
)
With jQuery or Javascript's querySelector
you have direct acess to formated data... Example:
<p>Elements for an average: <span class="m">2</span>, <span class="m">4</span>,
<span class="m">2</span>, <span class="m">3</span>.
</p>
So, with jQuery you have
var A = $('.m')
.map(function(idx) { return parseInt($(this).html()) })
.get();
var AVG = A.reduce(function(a,b){return a+b}) / A5.length;
See other more 4 ways (!) to access itens and average it: http://jsfiddle.net/4fLWB/
Try something like:
Add to html:
<link id="shortcutIcon" rel="shortcut icon" type="image/x-icon">
<link id="icon" rel="icon" type="image/x-icon">
Add minified script after tag:
<script type="text/javascript">
(function(b,c,d,a){a=c+d+b,document.getElementById('shortcutIcon').href=a,document.getElementById('icon').href=a;}(Math.random()*100,(document.querySelector('base')||{}).href,'/assets/images/favicon.ico?v='));
</script>
where
Before test clear history: (ctr + shfit + del)
Where does pip installations happen in python?
I will give a windows solution which I was facing and took a while to solve.
First of all, in windows (I will be taking Windows as the OS here), if you do pip install <package_name>
, it will be by default installed globally (if you have not activated a virtual enviroment).
Once you activate a virtual enviroment and you are inside it, all pip installations will be inside that virtual enviroment.
pip is installing the said packages but not I cannot use them?
For this pip might be giving you a warning that the pip executables like pip3.exe
, pip.exe
are not on your path variable.
For this you might add this path ( usually - C:\Users\<your_username>\AppData\Roaming\Programs\Python\
) to your enviromental variables.
After this restart your cmd
, and now try to use your installed python package. It should work now.
If you are on Mac and installed mysql through brew like me, the following worked.
cp $(brew --prefix mysql)/support-files/my-default.cnf /usr/local/etc/my.cnf
Source: For homebrew mysql installs, where's my.cnf?
add max_allowed_packet=1073741824
to /usr/local/etc/my.cnf
mysql.server restart
One use case is to make an ajax
call before the user closes the window or leaves the page. This would be like deleting some temporary records in the database before the user can navigate to another site or closes the browser.
$(window).unload(
function(){
$.ajax({
url: 'your url',
global: false,
type: 'POST',
data: {},
async: false, //blocks window close
success: function() {}
});
});
The simple approach (gcc -dM -E - < /dev/null
) works fine for gcc but fails for g++. Recently I required a test for a C++11/C++14 feature. Recommendations for their corresponding macro names are published at https://isocpp.org/std/standing-documents/sd-6-sg10-feature-test-recommendations. But:
g++ -dM -E - < /dev/null | fgrep __cpp_alias_templates
always fails, because it silently invokes the C-drivers (as if invoked by gcc
). You can see this by comparing its output against that of gcc or by adding a g++-specific command line option like (-std=c++11) which emits the error message cc1: warning: command line option ‘-std=c++11’ is valid for C++/ObjC++ but not for C
.
Because (the non C++) gcc will never support "Templates Aliases" (see http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2258.pdf) you must add the -x c++
option to force the invocation of the C++ compiler (Credits for using the -x c++
options instead of an empty dummy file go to yuyichao, see below):
g++ -dM -E -x c++ /dev/null | fgrep __cpp_alias_templates
There will be no output because g++ (revision 4.9.1, defaults to -std=gnu++98) does not enable C++11-features by default. To do so, use
g++ -dM -E -x c++ -std=c++11 /dev/null | fgrep __cpp_alias_templates
which finally yields
#define __cpp_alias_templates 200704
noting that g++ 4.9.1 does support "Templates Aliases" when invoked with -std=c++11
.
API Monitor looks very useful for this purpose.
df.loc[:,'industry'] = 'yyy'
This does the magic. You are to add '.loc' with ':' for all rows. Hope it helps
If you're not using the id
for anything other than code-behind reference (since .net mangles the ids), you could use a panel
control and reference it in your codebehind:
<asp:panel runat="server" id="classMe"></asp:panel>
classMe.cssClass = "someClass"
First, you need to make sure your server is configured to allow wildcard subdomains. I achieved that in JustHost by creating a subomain manually named *
. I also specified a folder called subdomains
as the document root for wildcard subdomains. Add this to a .htaccess
file in your subdomains folder:
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.website\.com$
RewriteCond %{HTTP_HOST} ^(\w+)\.website\.com$
RewriteCond %{REQUEST_URI}:%1 !^/([^/]+)/([^:]*):\1
RewriteRule ^(.*)$ /%1/$1 [QSA]
Finally, all you need to do is create a folder in your subdomains folder, then place the subdomain's files in that directory.
It will be better for you to write your code like this.
In your Controller Write this code.
function new_blank_order_summary() {
$query = $this->sales_model->order_summary_insert();
if($query) {
$this->load->view('sales/new_blank_order_summary');
} else {
$this->load->view('sales/data_insertion_failed');
}
}
and in your Model
function order_summary_insert() {
$orderLines = trim(xss_clean($this->input->post('orderlines')));
$customerName = trim(xss_clean($this->input->post('customer')));
$data = array(
'OrderLines'=>$orderLines,
'CustomerName'=>$customerName
);
$this->db->insert('Customer_Orders',$data);
return ($this->db->affected_rows() != 1) ? false : true;
}
You need to add path to svn.exe file to system environment, variable PATH, after that you can run command mvn from any folder. You can do it from command line(cmd.exe) like this, for example:
set PATH=%PATH%;C:\maven\bin
Or you can got to the folder where mvn.exe is, and run your command there.
And you need not mvn -version
, but mvn --version
parameter.
It doesn't work in IE5, but that's not a big issue.
However, cacheing headers are unreliable in meta elements; for one, any web proxies between the site and the user will completely ignore them. You should always use a real HTTP header for headers such as Cache-Control and Pragma.
First install openpyxl:
pip install openpyxl
Then:
from openpyxl import Workbook
import csv
wb = Workbook()
ws = wb.active
with open('test.csv', 'r') as f:
for row in csv.reader(f):
ws.append(row)
wb.save('name.xlsx')
Aside from the Random Class, which generates integers and doubles, consider:
Stack Overflow question Generation of (pseudo) random constrained values of (U)Int64 and Decimal
As of Bootstrap 4 this is now much easier using the included utilities instead of custom CSS. You simply have to add the class align-middle to the td-element:
<table>
<tbody>
<tr>
<td class="align-baseline">baseline</td>
<td class="align-top">top</td>
<td class="align-middle">middle</td>
<td class="align-bottom">bottom</td>
<td class="align-text-top">text-top</td>
<td class="align-text-bottom">text-bottom</td>
</tr>
</tbody>
</table>
Sometimes it is very convenient to use stringstream to convert between strings and other numerical types. The usage of stringstream
is similar to the usage of iostream
, so it is not a burden to learn.
Stringstreams can be used to both read strings and write data into strings. It mainly functions with a string buffer, but without a real I/O channel.
The basic member functions of stringstream class are
str()
, which returns the contents of its buffer in string type.
str(string)
, which set the contents of the buffer to the string argument.
Here is an example of how to use string streams.
ostringstream os;
os << "dec: " << 15 << " hex: " << std::hex << 15 << endl;
cout << os.str() << endl;
The result is dec: 15 hex: f
.
istringstream
is of more or less the same usage.
To summarize, stringstream is a convenient way to manipulate strings like an independent I/O device.
FYI, the inheritance relationships between the classes are:
You can also use:
function myFunction() {
var str = "xq234";
var allowChars = "^[a-zA-ZÀ-ÿ]+$";
var res = str.match(allowChars);
if(!str.match(allowChars)){
res="true";
}
else {
res="false";
}
document.getElementById("demo").innerHTML = res;
After a bit of struggle, I found a better solution.
create a directory with name: swagger
mkdir C:\swagger
If you are in Linux, try:
mkdir /opt/swagger
get swagger-editor with below command:
git clone https://github.com/swagger-api/swagger-editor.git
go into swagger-editor directory that is created now
cd swagger-editor
now get swagger-ui with below command:
git clone https://github.com/swagger-api/swagger-ui.git
now, copy your swagger file, I copied to below path:
./swagger-editor/api/swagger/swagger.json
all setup is done, run the swagger-edit with below commands
npm install
npm run build
npm start
You will be prompted 2 URLs, one of them might look like:
http://127.0.0.1:3001/
Above is swagger-editor URL
Now browse to:
http://127.0.0.1:3001/swagger-ui/dist/
Above is swagger-ui URL
Thats all.
You can now browse files from either of swagger-ui or swagger-editor
It will take time to install/build, but once done, you will see great results.
It took roughly 2 days of struggle for me, one-time installation took only about 5 minutes.
Now, on top-right, you can browse to your local file.
best of luck.
For passing multiple parameters you can cast the string by concatenating it with the ASCII value. Like, for single quotes we can use '
:
var str = "'" + str + "'";
The same parameter you can pass to the onclick()
event. In most of the cases it works with every browser.
The relevant build.gradle file will then update automatically.
Open your build.gradle file and add a new build rule to the dependencies closure. For example, if you wanted to add Google Play Services, your project's dependencies section would look something like this:
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.google.android.gms:play-services:6.5.+'
}
In the Project panel, Control + click the module you want to add the dependency to and select Open Module Settings.
Select the Dependencies tab, followed by the + button in the bottom-left corner. You can choose from the following list of options:
You can then enter more information about the dependency you want to add to your project. For example, if you choose Library Dependency, Android Studio displays a list of libraries for you to choose from.
Once you've added your dependency, check your module-level build.gradle file. It should have automatically updated to include the new dependency.
button {
width:1000px;
}
or even
button {
width:1000px !important
}
If thats what you mean
The first problem is that your query string is wrong:
I think this: "INSERT INTO employee(hans,germany) values(?,?)"
should be like this: "INSERT INTO employee(name,country) values(?,?)"
The other problem is that you have a parameterized PreparedStatement and you don't set the parameters before running it.
You should add these to your code:
String inserting = "INSERT INTO employee(name,country) values(?,?)";
System.out.println("insert " + inserting);//
PreparedStatement ps = con.prepareStatement(inserting);
ps.setString(1,"hans"); // <----- this
ps.setString(2,"germany");// <---- and this
ps.executeUpdate();
XmlDocument to read an XML from string or from file.
XmlDocument doc = new XmlDocument();
doc.Load("c:\\temp.xml");
or
doc.LoadXml("<xml>something</xml>");
then find a node below it ie like this
XmlNode node = doc.DocumentElement.SelectSingleNode("/book/title");
or
foreach(XmlNode node in doc.DocumentElement.ChildNodes){
string text = node.InnerText; //or loop through its children as well
}
then read the text inside that node like this
string text = node.InnerText;
or read an attribute
string attr = node.Attributes["theattributename"]?.InnerText
Always check for null on Attributes["something"] since it will be null if the attribute does not exist.
document.getElementById("address_box").value =
(title + "\n" + address + "\n" + address2 + "\n" + address3 + "\n" + address4);
You should have a look at moment
which is a python port of the excellent js lib momentjs
.
One advantage of it is the support of ISO 8601
strings formats, as well as a generic "% format" :
import moment
time_string='2012-10-09T19:00:55Z'
m = moment.date(time_string, '%Y-%m-%dT%H:%M:%SZ')
print m.format('YYYY-M-D H:M')
print m.weekday
Result:
2012-10-09 19:10
2
I would use the scheduler (control panel) rather than a cmd line or other application.
Control Panel -> Scheduled tasks
Queries should look like :
SHOW TABLES
SHOW TABLES FROM mydatabase
SHOW TABLES FROM mydatabase LIKE "tab%"
Things from the MySQL documentation in square brackets [] are optional.
NPM shrinkwrap offers a nice solution to this problem. It allows us to override that version of a particular dependency of a particular sub-module.
Essentially, when you run npm install, npm will first look in your root directory to see whether a npm-shrinkwrap.json file exists. If it does, it will use this first to determine package dependencies, and then falling back to the normal process of working through the package.json files.
To create an npm-shrinkwrap.json, all you need to do is
npm shrinkwrap --dev
code:
{
"dependencies": {
"grunt-contrib-connect": {
"version": "0.3.0",
"from": "[email protected]",
"dependencies": {
"connect": {
"version": "2.8.1",
"from": "connect@~2.7.3"
}
}
}
}
}
round() can take ints and negative numbers for places, which round to the left of the decimal. The return value is still a float, but a simple cast fixes that:
>>> int(round(5678,-1))
5680
>>> int(round(5678,-2))
5700
>>> int(round(5678,-3))
6000
I assume you are using TCP sockets for the client-server interaction? One way to send different types of data to the server and have it be able to differentiate between the two is to dedicate the first byte (or more if you have more than 256 types of messages) as some kind of identifier. If the first byte is one, then it is message A, if its 2, then its message B. One easy way to send this over the socket is to use DataOutputStream/DataInputStream
:
Client:
Socket socket = ...; // Create and connect the socket
DataOutputStream dOut = new DataOutputStream(socket.getOutputStream());
// Send first message
dOut.writeByte(1);
dOut.writeUTF("This is the first type of message.");
dOut.flush(); // Send off the data
// Send the second message
dOut.writeByte(2);
dOut.writeUTF("This is the second type of message.");
dOut.flush(); // Send off the data
// Send the third message
dOut.writeByte(3);
dOut.writeUTF("This is the third type of message (Part 1).");
dOut.writeUTF("This is the third type of message (Part 2).");
dOut.flush(); // Send off the data
// Send the exit message
dOut.writeByte(-1);
dOut.flush();
dOut.close();
Server:
Socket socket = ... // Set up receive socket
DataInputStream dIn = new DataInputStream(socket.getInputStream());
boolean done = false;
while(!done) {
byte messageType = dIn.readByte();
switch(messageType)
{
case 1: // Type A
System.out.println("Message A: " + dIn.readUTF());
break;
case 2: // Type B
System.out.println("Message B: " + dIn.readUTF());
break;
case 3: // Type C
System.out.println("Message C [1]: " + dIn.readUTF());
System.out.println("Message C [2]: " + dIn.readUTF());
break;
default:
done = true;
}
}
dIn.close();
Obviously, you can send all kinds of data, not just bytes and strings (UTF).
Note that writeUTF
writes a modified UTF-8 format, preceded by a length indicator of an unsigned two byte encoded integer giving you 2^16 - 1 = 65535
bytes to send. This makes it possible for readUTF
to find the end of the encoded string. If you decide on your own record structure then you should make sure that the end and type of the record is either known or detectable.
Your DOS command 2> nul
Read page Using command redirection operators. Besides the "2>" construct mentioned by Tanuki Software, it lists some other useful combinations.
RealVNC 5.0.x now offers a VNCViewer that will do dual displays on Windows without having to buy a license. (Licensing now covers the SERVER portion of their tools).
I had the same problem. You should type your Angular js code outside of any function like this:
$( document ).ready(function() {});
Every object in python has an identifier, Type, reference count associated with it, when we use del the reference count is reduced, when the reference count becomes zero it is a potential candidate for getting garbage collected. This differentiates the del when compared to setting an identifier to None. In later case it simply means the object is just left out wild( until we are out of scope in which case the count is reduced) and simply now the identifier point to some other object(memory location).
Try to follow these steps, easy and clean.
Ambiguous HTTP method for action. Actions require an explicit HttpMethod binding for Swagger 2.0.
"each endpoint should have the method (get/post/put/delete)
. Solution:
Revisit your each and every controller and make sure you have added expected method.
(or you can just see in console error which controller causing ambiguity)
This is more of a mathematical approach but it works 100% of the time:
Let's say you want to use random.random()
function to generate a number between a
and b
. To achieve this, just do the following:
num = (b-a)*random.random() + a;
Of course, you can generate more numbers.
I find it surprising that no one mentions data
as an object. For me it's the cleanest and easiest way to pass data:
$('form#foo').submit(function () {
$.ajax({
url: 'http://foo.bar/some-ajax-script',
type: 'POST',
dataType: 'json',
data: {
'foo': 'some-foo-value',
'bar': $('#bar').val()
}
}).always(function (response) {
console.log(response);
});
return false;
});
Then, in the backend:
// Example in PHP
$_POST['foo'] // some-foo-value
$_POST['bar'] // value in #bar
var d = $('.text_div');
d.text(d.text().trim().replace(/contains/i, "hello everyone"));
I'm on MBP , and install redis detail my problem was resolved .Fixed the Download, extract and compile Redis with:
$ wget http://download.redis.io/releases/redis-3.0.2.tar.gz
$ tar xzf redis-3.0.2.tar.gz
$ cd redis-3.0.2
$ make
The binaries that are now compiled are available in the src directory.
Run Redis with:
$ src/redis-server
This is what worked for me, for my case it was a post for login request :
var client = new RestClient("http://www.example.com/1/2");
var request = new RestRequest();
request.Method = Method.POST;
request.AddHeader("Accept", "application/json");
request.Parameters.Clear();
request.AddParameter("application/json", body , ParameterType.RequestBody);
var response = client.Execute(request);
var content = response.Content; // raw content as string
body :
{
"userId":"[email protected]" ,
"password":"welcome"
}
Converting String array into stream and mapping to int is the best option available in java 8.
String[] stringArray = new String[] { "0", "1", "2" };
int[] intArray = Stream.of(stringArray).mapToInt(Integer::parseInt).toArray();
System.out.println(Arrays.toString(intArray));