sqlcmd -S myServer -d myDB -E -o "MyData.txt" ^
-Q "select bar from foo" ^
-W -w 999 -s","
The last line contains CSV-specific options.
-W
remove trailing spaces from each individual field-s","
sets the column seperator to the comma (,) -w 999
sets the row width to 999 charsscottm's answer is very close to what I use, but I find the -W
to be a really nice addition: I needn't trim whitespace when I consume the CSV elsewhere.
Also see the MSDN sqlcmd reference. It puts the /?
option's output to shame.
Its actually enough to add -m to startup parameters on Sql Server Configuration Manager, restart service, go to ssms an add checkbox sysadmin on your account, then remove -m restart again and use as usual.
Database Engine Service Startup Options
-m Starts an instance of SQL Server in single-user mode.
If you can not use Management studio i use sqlcmd.
sqlcmd -q "select col1,col2,col3 from table" -oc:\myfile.csv -h-1 -s","
That is the fast way to do it from command line.
Make sure to delete java references from system32, SysWOW64, and delete javapath from ProgramData\Oracle\Java. It solves the issue
gcc under cygwin does not generate a Linux executable output file of type " ELF 32-bit LSB executable," but it generates a windows executable of type "PE32 executable for MS Windows" which has a dependency on cygwin1.dll, so it needs to be run under cygwin shell. If u need to run it under dos prompt independently, they cygwin1.dll needs to be in your Windows PATH.
-AD.
I need to add my 5 cents. I see everybody use [
or [[
, but it worth to mention that they are not part of if syntax.
For arithmetic comparisons, use ((...))
instead.
((...)) is an arithmetic command, which returns an exit status of 0 if the expression is nonzero, or 1 if the expression is zero. Also used as a synonym for "let", if side effects (assignments) are needed.
See: ArithmeticExpression
this configuration in app.js worked fine for me :
//production mode
if (process.env.NODE_ENV === "production") {
app.use(express.static(path.join(__dirname, "client/build")));
app.get("*", (req, res) => {
res.sendFile(path.join((__dirname + "/client/build/index.html")));
});
}
//build mode
app.get("*", (req, res) => {
res.sendFile(path.join(__dirname + "/client/public/index.html"));
});
This one works fine for me with apis
import requests
data={'Id':id ,'name': name}
r = requests.post( url = 'https://apiurllink', data = data)
According to RFC 4337 § 2, video/mp4
is indeed the correct Content-Type for MPEG-4 video.
Generally, you can find official MIME definitions by searching for the file extension and "IETF" or "RFC". The RFC (Request for Comments) articles published by the IETF (Internet Engineering Taskforce) define many Internet standards, including MIME types.
Yep, that's definitely possible. The v$sql views contain that info. Something like this piece of code should point you in the right direction. I haven't tried that specific piece of code myself - nowhere near an Oracle DB right now.
[Edit] Damn two other answers already. Must type faster next time ;-)
There's more to it than this, but you're probably looking for this list:
B business day frequency
C custom business day frequency (experimental)
D calendar day frequency
W weekly frequency
M month end frequency
BM business month end frequency
MS month start frequency
BMS business month start frequency
Q quarter end frequency
BQ business quarter endfrequency
QS quarter start frequency
BQS business quarter start frequency
A year end frequency
BA business year end frequency
AS year start frequency
BAS business year start frequency
H hourly frequency
T minutely frequency
S secondly frequency
L milliseconds
U microseconds
Source: http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases
As per String literals:
String literals can be enclosed within single quotes (i.e.
'...'
) or double quotes (i.e."..."
). They can also be enclosed in matching groups of three single or double quotes (these are generally referred to as triple-quoted strings).The backslash character (i.e.
\
) is used to escape characters which otherwise will have a special meaning, such as newline, backslash itself, or the quote character. String literals may optionally be prefixed with a letterr
orR
. Such strings are called raw strings and use different rules for backslash escape sequences.In triple-quoted strings, unescaped newlines and quotes are allowed, except that the three unescaped quotes in a row terminate the string.
Unless an
r
orR
prefix is present, escape sequences in strings are interpreted according to rules similar to those used by Standard C.
So ideally you need to replace the line:
data = open("C:\Users\miche\Documents\school\jaar2\MIK\2.6\vektis_agb_zorgverlener")
To any one of the following characters:
Using raw prefix and single quotes (i.e. '...'
):
data = open(r'C:\Users\miche\Documents\school\jaar2\MIK\2.6\vektis_agb_zorgverlener')
Using double quotes (i.e. "..."
) and escaping backslash character (i.e. \
):
data = open("C:\\Users\\miche\\Documents\\school\\jaar2\\MIK\\2.6\\vektis_agb_zorgverlener")
Using double quotes (i.e. "..."
) and forwardslash character (i.e. /
):
data = open("C:/Users/miche/Documents/school/jaar2/MIK/2.6/vektis_agb_zorgverlener")
As Davide Gualano has been told. This one
$("#myDiv").load("myScript.php?var=x&var2=y&var3=z")
use GET method for sending the request, and this one
$("#myDiv").load("myScript.php", {var:x, var2:y, var3:z})
use POST method for sending the request. But any limitation that is applied to each method (post/get) is applied to the alternative usages that has been mentioned in the question.
For example: url length limits the amount of sending data in GET method.
Parameters are key-value pairs that can appear inside URL path, and start with a semicolon character (;
).
Query string appears after the path (if any) and starts with a question mark character (?
).
Both parameters and query string contain key-value pairs.
In a GET
request, parameters appear in the URL itself:
<scheme>://<username>:<password>@<host>:<port>/<path>;<parameters>?<query>#<fragment>
In a POST
request, parameters can appear in the URL itself, but also in the datastream (as known as content).
Query string is always a part of the URL.
Parameters can be buried in form-data
datastream when using POST method so they may not appear in the URL. Yes a POST
request can define parameters as form data and in the URL, and this is not inconsistent because parameters can have several values.
I've found no explaination for this behavior so far. I guess it might be useful sometimes to "unhide" parameters from a POST
request, or even let the code handling a GET
request share some parts with the code handling a POST
. Of course this can work only with server code supporting parameters in a URL.
Until you get better insights, I suggest you to use parameters only in form-data
datastream of POST
requests.
Sources:
This is a simple tutorial on creating csv files using C# that you will be able to edit and expand on to fit your own needs.
First you’ll need to create a new Visual Studio C# console application, there are steps to follow to do this.
The example code will create a csv file called MyTest.csv in the location you specify. The contents of the file should be 3 named columns with text in the first 3 rows.
https://tidbytez.com/2018/02/06/how-to-create-a-csv-file-with-c/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace CreateCsv
{
class Program
{
static void Main()
{
// Set the path and filename variable "path", filename being MyTest.csv in this example.
// Change SomeGuy for your username.
string path = @"C:\Users\SomeGuy\Desktop\MyTest.csv";
// Set the variable "delimiter" to ", ".
string delimiter = ", ";
// This text is added only once to the file.
if (!File.Exists(path))
{
// Create a file to write to.
string createText = "Column 1 Name" + delimiter + "Column 2 Name" + delimiter + "Column 3 Name" + delimiter + Environment.NewLine;
File.WriteAllText(path, createText);
}
// This text is always added, making the file longer over time
// if it is not deleted.
string appendText = "This is text for Column 1" + delimiter + "This is text for Column 2" + delimiter + "This is text for Column 3" + delimiter + Environment.NewLine;
File.AppendAllText(path, appendText);
// Open the file to read from.
string readText = File.ReadAllText(path);
Console.WriteLine(readText);
}
}
}
You can Change it from:
Menu Settings -> Style Configurator
See on screenshot:
Since iOS 8 came out, this problem does not exist any more. The scroll event is now fired smoothly in iOS Safari as well.
So, if you register the scroll
event handler and check window.pageYOffset
inside that event handler, everything works just fine.
Read-Host
is a simple option for getting string input from a user.
$name = Read-Host 'What is your username?'
To hide passwords you can use:
$pass = Read-Host 'What is your password?' -AsSecureString
To convert the password to plain text:
[Runtime.InteropServices.Marshal]::PtrToStringAuto(
[Runtime.InteropServices.Marshal]::SecureStringToBSTR($pass))
As for the type returned by $host.UI.Prompt()
, if you run the code at the link posted in @Christian's comment, you can find out the return type by piping it to Get-Member
(for example, $results | gm
). The result is a Dictionary where the key is the name of a FieldDescription
object used in the prompt. To access the result for the first prompt in the linked example you would type: $results['String Field']
.
To access information without invoking a method, leave the parentheses off:
PS> $Host.UI.Prompt
MemberType : Method
OverloadDefinitions : {System.Collections.Generic.Dictionary[string,psobject] Pr
ompt(string caption, string message, System.Collections.Ob
jectModel.Collection[System.Management.Automation.Host.Fie
ldDescription] descriptions)}
TypeNameOfValue : System.Management.Automation.PSMethod
Value : System.Collections.Generic.Dictionary[string,psobject] Pro
mpt(string caption, string message, System.Collections.Obj
ectModel.Collection[System.Management.Automation.Host.Fiel
dDescription] descriptions)
Name : Prompt
IsInstance : True
$Host.UI.Prompt.OverloadDefinitions
will give you the definition(s) of the method. Each definition displays as <Return Type> <Method Name>(<Parameters>)
.
Renders the HTML widget of a given field. If you apply this to an entire form or collection of fields, each underlying form row will be rendered.
{# render a field row, but display a label with text "foo" #}
{{ form_row(form.name, {'label': 'foo'}) }}
The second argument to form_row() is an array of variables. The templates provided in Symfony only allow to override the label as shown in the example above.
See "More about Form Variables" to learn about the variables argument.
In java8 fashion:
import java.util.Arrays;
public class MatrixPrinter {
public static void main(String[] args) {
final int[][] matrix = new int[4][4];
printMatrix(matrix);
}
public static void printMatrix(int[][] matrix) {
Arrays.stream(matrix)
.forEach(
(row) -> {
System.out.print("[");
Arrays.stream(row)
.forEach((el) -> System.out.print(" " + el + " "));
System.out.println("]");
}
);
}
}
this produces
[ 0 0 0 0 ]
[ 0 0 0 0 ]
[ 0 0 0 0 ]
[ 0 0 0 0 ]
but since we are here why not make the row layout customisable?
All we need is to pass a lamba to the matrixPrinter method:
import java.util.Arrays;
import java.util.function.Consumer;
public class MatrixPrinter {
public static void main(String[] args) {
final int[][] matrix = new int[3][3];
Consumer<int[]> noDelimiter = (row) -> {
Arrays.stream(row).forEach((el) -> System.out.print(" " + el + " "));
System.out.println();
};
Consumer<int[]> pipeDelimiter = (row) -> {
Arrays.stream(row).forEach((el) -> System.out.print("| " + el + " "));
System.out.println("|");
};
Consumer<int[]> likeAList = (row) -> {
System.out.print("[");
Arrays.stream(row)
.forEach((el) -> System.out.print(" " + el + " "));
System.out.println("]");
};
printMatrix(matrix, noDelimiter);
System.out.println();
printMatrix(matrix, pipeDelimiter);
System.out.println();
printMatrix(matrix, likeAList);
}
public static void printMatrix(int[][] matrix, Consumer<int[]> rowPrinter) {
Arrays.stream(matrix)
.forEach((row) -> rowPrinter.accept(row));
}
}
this is the result :
0 0 0
0 0 0
0 0 0
| 0 | 0 | 0 |
| 0 | 0 | 0 |
| 0 | 0 | 0 |
[ 0 0 0 ]
[ 0 0 0 ]
[ 0 0 0 ]
Why not just fix the condition in your while loop, causing the problem to disappear?
while(msg->state != DONE)
{
switch(msg->state) {
case MSGTYPE: // ...
break;
// ... more stuff ...
case DONE:
// We can't get here, but for completeness we list it.
break; // **HERE, I want to break out of the loop itself**
}
}
First of all, you need to check that the IIS is installed in your machine, for that you can go to:
Control Panel --> Add or Remove Programs --> Windows Features --> And Check if Internet Information Services is installed with at least the 'Web Administration Tools' Enabled and The 'World Wide Web Service'
If not, check it, and Press Accept to install it.
Once that is done, you need to go to Administrative Tools in Control Panel and the IIS Will be there. Or simply run inetmgr (after Win+R).
Edit: You should have something like this:
To answer your question. I would say it's fairly common for applications to replace spaces in values that will be used in URLs. The reason for this is ussually to avoid the more difficult to read percent (URI) encoding that occurs.
Check out this wikipedia article about Percent-encoding.
also.. try to "clean" your projects or solution and rebuild again!
http://forums.devshed.com/mysql-help-4/mysql-installation-problems-197509.html
It says to rename the ib_* files. I have done it and it gave me back the db.
#!/usr/bin/env ruby
=begin
Between =begin and =end, any number
of lines may be written. All of these
lines are ignored by the Ruby interpreter.
=end
puts "Hello world!"
Also use NVL2
as below if you want to return other value from the field_to_check
:
NVL2( field_to_check, value_if_NOT_null, value_if_null )
Usage: ORACLE/PLSQL: NVL2 FUNCTION
Best way to install nodejs is through NVM (Node Version Manager)
Delete previous versions :
$ sudo apt-get purge node
$ sudo apt autoremove
Also delete all node_modules by $ sudo rm -rf node_modules
in the directory containing this folder.
Node & Nodejs are technically the same thing. Just the naming changed.
First Install or update nvm
to run as root
$ sudo su
Then
$ curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.31.7/install.sh | bash
OR
$ wget -qO- https://raw.githubusercontent.com/creationix/nvm/v0.31.7/install.sh | bash
Check nvm to path
$ source ~/.profile
$ nvm ls-remote
if you get error regarding the listing then install git.
$ sudo apt-get install git
Re-run :
$ nvm ls-remoteOR
$ sudo nvm ls-remote
$ nvm install version-you-require
Checking Version
# node --version
nvm use version-you-require
INFORMATION COURTESY :
https://www.digitalocean.com/community/tutorials/how-to-install-node-js-with-nvm-node-version-manager-on-a-vps
mysqli_select_db()
should have 2 parameters, the connection link and the database name -
mysqli_select_db($con, 'phpcadet') or die(mysqli_error($con));
Using mysqli_error
in the die statement will tell you exactly what is wrong as opposed to a generic error message.
PHP has ssh2 stream wrappers (disabled by default), so you can use sftp connections with any function that supports stream wrappers by using ssh2.sftp://
for protocol, e.g.
file_get_contents('ssh2.sftp://user:[email protected]:22/path/to/filename');
or - when also using the ssh2 extension
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');
$sftp = ssh2_sftp($connection);
$stream = fopen("ssh2.sftp://$sftp/path/to/file", 'r');
See http://php.net/manual/en/wrappers.ssh2.php
On a side note, there is also quite a bunch of questions about this topic already:
It is true that, functionally, both queries should be processed the same way. However, experience has shown that if you are selecting from views that use the new join syntax, it is important to structure your queries using it as well. Oracle's optimizer can get confused if a view uses a "join" statement, but a query accessing the view uses the traditional method of joining in the "where" clause.
I started to go this route, but I have my own navigation control with a core view
that I slide into a frame that's usually wrapping the core with a common title bar and tabbar
; no storyboard
, no UINavigationController
.
It started to get complicated fast, adding and subtracting the 20 pixels of the status bar. Then an epiphany.
I made a copy of the .xib file
, told Xcode
to show it to me as an iOS 7 layout, realigned everything, and put a single 6/7 switch in code .. instantly, everything works right, and the additional resources add only 8K to the bundle.
An other example would be on the "created_on" column where you want to let the database handle the date creation
Hyper Text Transfer Protocol (HTTP) is a protocol used for transferring web pages (like the one you're reading right now). A protocol is really nothing but a standard way of doing things. If you were to meet the President of the United States, or the king of a country, there would be specific procedures that you'd have to follow. You couldn't just walk up and say "hey dude". There would be a specific way to walk, to talk, a standard greeting, and a standard way to end the conversation. Protocols in the TCP/IP stack serve the same purpose.
The TCP/IP stack has four layers: Application, Transport, Internet, and Network. At each layer there are different protocols that are used to standardize the flow of information, and each one is a computer program (running on your computer) that's used to format the information into a packet as it's moving down the TCP/IP stack. A packet is a combination of the Application Layer data, the Transport Layer header (TCP or UDP), and the IP layer header (the Network Layer takes the packet and turns it into a frame).
...consists of all applications that use the network to transfer data. It does not care about how the data gets between two points and it knows very little about the status of the network. Applications pass data to the next layer in the TCP/IP stack and then continue to perform other functions until a reply is received. The Application Layer uses host names (like www.dalantech.com) for addressing. Examples of application layer protocols: Hyper Text Transfer Protocol (HTTP -web browsing), Simple Mail Transfer Protocol (SMTP -electronic mail), Domain Name Services (DNS -resolving a host name to an IP address), to name just a few.
The main purpose of the Application Layer is to provide a common command language and syntax between applications that are running on different operating systems -kind of like an interpreter. The data that is sent by an application that uses the network is formatted to conform to one of several set standards. The receiving computer can understand the data that is being sent even if it is running a different operating system than the sender due to the standards that all network applications conform to.
...is responsible for assigning source and destination port numbers to applications. Port numbers are used by the Transport Layer for addressing and they range from 1 to 65,535. Port numbers from 0 to 1023 are called "well known ports". The numbers below 256 are reserved for public (standard) services that run at the Application Layer. Here are a few: 25 for SMTP, 53 for DNS (udp for domain resolution and tcp for zone transfers) , and 80 for HTTP. The port numbers from 256 to 1023 are assigned by the IANA to companies for the applications that they sell.
Port numbers from 1024 to 65,535 are used for client side applications -the web browser you are using to read this page, for example. Windows will only assign port numbers up to 5000 -more than enough port numbers for a Windows based PC. Each application has a unique port number assigned to it by the transport layer so that as data is received by the Transport Layer it knows which application to give the data to. An example is when you have more than one browser window running. Each window is a separate instance of the program that you use to surf the web, and each one has a different port number assigned to it so you can go to www.dalantech.com in one browser window and this site does not load into another browser window. Applications like FireFox that use tabbed windows simply have a unique port number assigned to each tab
...is the "glue" that holds networking together. It permits the sending, receiving, and routing of data.
...consists of your Network Interface Card (NIC) and the cable connected to it. It is the physical medium that is used to transmit and receive data. The Network Layer uses Media Access Control (MAC) addresses, discussed earlier, for addressing. The MAC address is fixed at the time an interface was manufactured and cannot be changed. There are a few exceptions, like DSL routers that allow you to clone the MAC address of the NIC in your PC.
For more info:
I had a big dataset and .loc[] was taking too long so I found a vectorized way to do it. Recall that you can set a column to a logical operator, so this works:
file['Flag'] = (file['Claim_Amount'] > 0)
This gives a Boolean, which I wanted, but you can multiply it by, say, 1 to make an Integer.
The problem seems to be a mis-placed )
. In your sample you have the %
outside of the print()
, you should move it inside:
Use this:
print("%s. %s appears %s times." % (str(i), key, str(wordBank[key])))
Before running your app, you can do this in console,
export NODE_ENV=production
Or if you are in windows you could try this:
SET NODE_ENV=production
for PowerShell:
$env:NODE_ENV="production"
or you can run your app like this:
NODE_ENV=production node app.js
You can also set it in your js file:
process.env.NODE_ENV = 'production';
But I don't suggest to do it in your runtime file, since it's not easy to open up VIM in your server and change it to production. You can make a config.json file in your directory and everytime your app runs, it reads from it and sets the configuration.
From the documentation about ASP.NET Web Project Folder Structure in MSDN:
You can keep your Web project's files in any folder structure that is convenient for your application. To make it easier to work with your application, ASP.NET reserves certain file and folder names that you can use for specific types of content.
App_Data contains application data files including .mdf database files, XML files, and other data store files. The App_Data folder is used by ASP.NET to store an application's local database, such as the database for maintaining membership and role information. For more information, see Introduction to Membership and Understanding Role Management.
I know this answer is a bit late.
My purpose for this answer is for everyone's reference should they encounter this type of challenge with SQLite now or in the future and they're having a hard time with it.
Now, looking back at your query, it should be something like this.
CREATE TABLE people (id integer primary key autoincrement, first_name varchar(20), last_name varchar(20));
It works on my end. Like so,
Just in case you are working with SQLite, I suggest for you to check out DB Browser for SQLite. Works on different platforms as well.
Simplified example of Nicolai Ehmann's comment and wildloop's answer (works with Spring 4.3.3+), basically you can use required = false
now:
@RequestMapping(value = {"/json/{type}", "/json" }, method = RequestMethod.GET)
public @ResponseBody TestBean testAjax(@PathVariable(required = false) String type) {
if (type != null) {
// ...
}
return new TestBean();
}
Must it be mutable? Use a list. Must it not be mutable? Use a tuple.
Otherwise, it's a question of choice.
For collections of heterogeneous objects (like a address broken into name, street, city, state and zip) I prefer to use a tuple. They can always be easily promoted to named tuples.
Likewise, if the collection is going to be iterated over, I prefer a list. If it's just a container to hold multiple objects as one, I prefer a tuple.
This works for me:
put this in your markup:
<div class="panel panel-default" [ngStyle]="{'background-image': getUrl()}">
then in component:
getUrl()
{
return "url('http://estringsoftware.com/wp-content/uploads/2017/07/estring-header-lowsat.jpg')";
}
You can't, you'll have to do something like
<script type="text/javascript">
var php_var = "<?php echo $php_var; ?>";
</script>
You can also load it with AJAX
rhino is right, the snippet lacks of a type for the sake of brevity.
Also, note that if $php_var
has quotes, it will break your script. You shall use addslashes, htmlentities or a custom function.
To anyone seeing this later on, as it currently (Aug. 2017) tops google: It is worth mentioning, that this behavior will be altered in Rails 5.2, and has deprecation warnings as of Rails 5.1, as ActiveModel::Dirty changed a bit.
What do I change?
If you're using attribute_changed?
method in the after_*
-callbacks, you'll see a warning like:
DEPRECATION WARNING: The behavior of
attribute_changed?
inside of after callbacks will be changing in the next version of Rails. The new return value will reflect the behavior of calling the method aftersave
returned (e.g. the opposite of what it returns now). To maintain the current behavior, usesaved_change_to_attribute?
instead. (called from some_callback at /PATH_TO/app/models/user.rb:15)
As it mentions, you could fix this easily by replacing the function with saved_change_to_attribute?
. So for example, name_changed?
becomes saved_change_to_name?
.
Likewise, if you're using the attribute_change
to get the before-after values, this changes as well and throws the following:
DEPRECATION WARNING: The behavior of
attribute_change
inside of after callbacks will be changing in the next version of Rails. The new return value will reflect the behavior of calling the method aftersave
returned (e.g. the opposite of what it returns now). To maintain the current behavior, usesaved_change_to_attribute
instead. (called from some_callback at /PATH_TO/app/models/user.rb:20)
Again, as it mentions, the method changes name to saved_change_to_attribute
which returns ["old", "new"]
.
or use saved_changes
, which returns all the changes, and these can be accessed as saved_changes['attribute']
.
There is no such thing as a silver bullet.
A single metric like that is useless by itself.
For instance, I have my own class library. Currently, the following statistics are true:
Total lines: 252.682
Code lines: 127.323
Comments: 99.538
Empty lines: 25.821
Let's assume I don't write any comments at all, that is, 127.323 lines of code. With your ratio, that code library would take me around 10610 days to write. That's 29 years.
I certainly didn't spend 29 years writing that code, since it's all C#, and C# hasn't been around that long.
Now, you can argue that the code isn't all that good, since obviously I must've surpassed your 12 lines a day metric, and yes, I'll agree to that, but if I'm to bring the timeline down to when 1.0 was released (and I didn't start actually making it until 2.0 was released), which is 2002-02-13, about 2600 days, the average is 48 lines of code a day.
All of those lines of code are good? Heck no. But down to 12 lines of code a day?
Heck no.
Everything depends.
You can have a top notch programmer churning out code in the order of thousands of lines a day, and a medium programmer churning out code in the order of hundreds of lines a day, and the quality is the same.
And yes, there will be bugs.
The total you want is the balance. Amount of code changed, versus the number of bugs found, versus the complexity of the code, versus the hardship of fixing those bugs.
export your C++ functions as extern "C" (aka C style symbols), or use the .def file format to define undecorated export symbols for the C++ linker when it creates the C++ library, then the C linker should have no troubles reading it
There is the Jquery alert plugin
$.alerts.okButton = ' Yes ';
$.alerts.cancelButton = ' No ';
You can use the Object.keys built-in method:
var sorted_keys = Object.keys(a).sort()
(Note: this does not work in very old browsers not supporting EcmaScript5, notably IE6, 7 and 8. For detailed up-to-date statistics, see this table)
Do not implement ft.addToBackStack() method so that when you pressed back button your activity will be finished.
proAddAccount = new ProfileAddAccount();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, proAddAccount);
//fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
Drupal 7 also has an easy solution here, this will allow you to validate against multiple countries.
https://drupal.org/project/postal_code_validation
You will need this module as well
https://drupal.org/project/postal_code
Test it in http://simplytest.me/
Use driver.save_screenshot('/path/to/file')
or driver.get_screenshot_as_file('/path/to/file')
:
import selenium.webdriver as webdriver
import contextlib
@contextlib.contextmanager
def quitting(thing):
yield thing
thing.quit()
with quitting(webdriver.Firefox()) as driver:
driver.implicitly_wait(10)
driver.get('http://www.google.com')
driver.get_screenshot_as_file('/tmp/google.png')
# driver.save_screenshot('/tmp/google.png')
Differences:
1) Implicit wait is set for the entire duration of the webDriver object. Suppose , you want to wait for a certain duration, let's say 5 seconds before each element or a lot of elements on the webpage load. Now, you wouldn't want to write the same code again and again. Hence, implicit wait. However, if you want to wait for only one element, use explicit.
2) You not only need web element to show up but also to be clickable or to satisfy certain other property of web elements. Such kind of flexibility can be provided by explicit wait only. Specially helpful if dynamic data is being loaded on webpage. You can wait for that element to be developed (not just show up on DOM) using explicit wait.
For most use cases, what about
from datetime import date
current_date =date.today()
current_month = current_date.month
last_month = current_month - 1 if current_month != 1 else 12
today_a_month_ago = date(current_date.year, last_month, current_date.day)
That seems the simplest to me.
Note: I've added the second to last line so that it would work if the current month is January as per @Nick's comment
Note 2: In most cases, if the current date is the 31st of a given month the result will be an invalid date as the previous month would not have 31 days (Except for July & August), as noted by @OneCricketeer
"If you want to Select multiple Cells and Copy their values to the Clipboard without all those annoying quotes" (without the bugs in Peter Smallwood's multi-Cells solution) "the following code may be useful." This is an enhancement of the code given above from Peter Smallwood (which "is an enhancement of the code given above from user3616725"). This fixes the following bugs in Peter Smallwood's solution:
NOTE: You still won't be able to copy characters embedded within a Cell that would cause an exit of the target field you're Pasting that Cell into (i.e. Tab or CR when Pasting into the Edit Table Window of Access or SSMS).
Option Explicit
Sub CopyCellsWithoutAddingQuotes()
' -- Attach Microsoft Forms 2.0 Library: tools\references\Browse\FM20.DLL
' -- NOTE: You may have to temporarily insert a UserForm into your VBAProject for it to show up.
' -- Then set a Keyboard Shortcut to the "CopyCellsWithoutAddingQuotes" Macro (i.e. Crtl+E)
Dim clibboardFieldDelimiter As String
Dim clibboardLineDelimiter As String
Dim row As Range
Dim cell As Range
Dim cellValueText As String
Dim clipboardText As String
Dim isFirstRow As Boolean
Dim isFirstCellOfRow As Boolean
Dim dataObj As New dataObject
clibboardFieldDelimiter = Chr(9)
clibboardLineDelimiter = Chr(13) + Chr(10)
isFirstRow = True
isFirstCellOfRow = True
For Each row In Selection.Rows
If Not isFirstRow Then
clipboardText = clipboardText + clibboardLineDelimiter
End If
For Each cell In row.Cells
If IsEmpty(cell.Value) Then
cellValueText = ""
ElseIf IsNumeric(cell.Value) Then
cellValueText = LTrim(Str(cell.Value))
Else
cellValueText = cell.Value
End If ' -- Else Non-empty Non-numeric
If isFirstCellOfRow Then
clipboardText = clipboardText + cellValueText
isFirstCellOfRow = False
Else ' -- Not (isFirstCellOfRow)
clipboardText = clipboardText + clibboardFieldDelimiter + cellValueText
End If ' -- Else Not (isFirstCellOfRow)
Next cell
isFirstRow = False
isFirstCellOfRow = True
Next row
clipboardText = clipboardText + clibboardLineDelimiter
dataObj.SetText (clipboardText)
dataObj.PutInClipboard
End Sub
Steps to manually configure DNS:
You can access Network and Sharing center by right clicking on the Network icon on the taskbar.
Now choose adapter settings from the side menu.
This will give you a list of the available network adapters in the system . From them right click on the adapter you are using to connect to the internet now and choose properties option.
In the networking tab choose ‘Internet Protocol Version 4 (TCP/IPv4)’.
Now you can see the properties dialogue box showing the properties of IPV4. Here you need to change some properties.
Select ‘use the following DNS address’ option. Now fill the following fields as given here.
Preferred DNS server: 208.67.222.222
Alternate DNS server : 208.67.220.220
This is an available Open DNS address. You may also use google DNS server addresses.
After filling these fields. Check the ‘validate settings upon exit’ option. Now click OK.
You have to add this DNS server address in the router configuration also (by referring the router manual for more information).
Refer : for above method & alternative
If none of this works, then open command prompt(Run as Administrator) and run these:
ipconfig /flushdns
ipconfig /registerdns
ipconfig /release
ipconfig /renew
NETSH winsock reset catalog
NETSH int ipv4 reset reset.log
NETSH int ipv6 reset reset.log
Exit
Hopefully that fixes it, if its still not fixed there is a chance that its a NIC related issue(driver update or h/w).
Also FYI, this has a thread on Microsoft community : Windows 10 - DNS Issue
if Number > 19 and Number < 99:
textNumber = str(Number)
firstDigit, secondDigit = textNumber
firstWord = num2words2[int(firstDigit)]
secondWord = num2words1[int(secondDigit)]
word = firstWord + secondWord
if Number <20 and Number > 0:
word = num2words1[Number]
if Number > 99:
error
I came here looking or the same idea, and in the meantime i came up with own, which I believe is not that bad and works if with ViewPager.
So what I did, is to override the onBackPressed method in the parent activity that holds the viewPager, and set it to always go back minus 1 position until it reaches the first fragment, then closes the activity.
@Override
public void onBackPressed() {
if(viewPager.getCurrentItem()>0){
viewPager.setCurrentItem(viewPager.getCurrentItem()-1);
} else {
super.onBackPressed();
this.close();
}
}
private void close(){
this.finish();
}
This might have a downfalls, like it only goes back one way left each time, so it might not work great if there are tabs and you switch positions with fragments skipped, ( going from 0 to 2, and then pressing back would put you on 1, instead of 0)
For my case tho, with 2 fragments in viewPager without tabs, it does the job nicely.
First convert this structure to a "dictionary" object:
dict = {}
json.forEach(function(x) {
dict[x.code] = x.name
})
and then simply
countryName = dict[countryCode]
For a list of countries this doesn't matter much, but for larger lists this method guarantees the instant lookup, while the naive searching will depend on the list size.
You can use sed
:
sed 's/^[^ ][^ ]* [^ ][^ ]* //'
This looks for lines starting with one-or-more non-blanks, a blank, another set of one-or-more non-blanks and another blank, and deletes the matched material, aka the first two fields. The [^ ][^ ]*
is marginally shorter than the equivalent but more explicit [^ ]\{1,\}
notation, and the second might run into issues with GNU sed
(though if you use --posix
as an option, even GNU sed
can't screw it up). OTOH, if the character class to be repeated was more complex, the numbered notation wins for brevity. It is easy to extend this to handle 'blank or tab' as separator, or 'multiple blanks' or 'multiple blanks or tabs'. It could also be modified to handle optional leading blanks (or tabs) before the first field, etc.
For awk
and cut
, see Sampson-Chen's answer. There are other ways to write the awk
script, but they're not materially better than the answer given. Note that you might need to set the field separator explicitly (-F" "
) in awk
if you do not want tabs treated as separators, or you might have multiple blanks between fields. The POSIX standard cut
does not support multiple separators between fields; GNU cut
has the useful but non-standard -i
option to allow for multiple separators between fields.
You can also do it in pure shell:
while read junk1 junk2 residue
do echo "$residue"
done < in-file > out-file
This Worked For Me. I have installed wordpress in godaddy shared server. Open .htaccess file using editor and add the following from the first line,
# BEGIN Increases Max Upload Size
php_value upload_max_filesize 20M
php_value post_max_size 20M
php_value max_execution_time 300
php_value max_input_time 300
# END Increases Max Upload Size
This solved the php.ini issues for me in the server.
The command line tool ExifTool by Phil Harvey works with dozens of images formats - including plenty of proprietary RAW formats - and can manipulate a variety of metadata formats including EXIF, GPS, IPTC, XMP, JFIF.
Very easy to use, lightweight, impressive application.
I have done something similar.
In your MyAdapter
:
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public CardView mCardView;
public TextView mTextViewTitle;
public TextView mTextViewContent;
public ImageView mImageViewContentPic;
public ImageView imgViewRemoveIcon;
public ViewHolder(View v) {
super(v);
mCardView = (CardView) v.findViewById(R.id.card_view);
mTextViewTitle = (TextView) v.findViewById(R.id.item_title);
mTextViewContent = (TextView) v.findViewById(R.id.item_content);
mImageViewContentPic = (ImageView) v.findViewById(R.id.item_content_pic);
//......
imgViewRemoveIcon = (ImageView) v.findViewById(R.id.remove_icon);
mTextViewContent.setOnClickListener(this);
imgViewRemoveIcon.setOnClickListener(this);
v.setOnClickListener(this);
mTextViewContent.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View view) {
if (mItemClickListener != null) {
mItemClickListener.onItemClick(view, getPosition());
}
return false;
}
});
}
@Override
public void onClick(View v) {
//Log.d("View: ", v.toString());
//Toast.makeText(v.getContext(), mTextViewTitle.getText() + " position = " + getPosition(), Toast.LENGTH_SHORT).show();
if(v.equals(imgViewRemoveIcon)){
removeAt(getPosition());
}else if (mItemClickListener != null) {
mItemClickListener.onItemClick(v, getPosition());
}
}
}
public void setOnItemClickListener(final OnItemClickListener mItemClickListener) {
this.mItemClickListener = mItemClickListener;
}
public void removeAt(int position) {
mDataset.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, mDataSet.size());
}
Hope this helps.
Edit:
getPosition()
is deprecated now, use getAdapterPosition()
instead.
I have fixed the same issue with below steps
php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
php -r "if (hash_file('SHA384', 'composer-setup.php') === 'the-provided-hash-code') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"
php composer-setup.php php -r "unlink('composer-setup.php');"
Everything is working fine now because the composer.phar
file is available within the current project directory.
Copied from https://stackoverflow.com/questions/21670709/running-composer-returns-could-not-open-input-file-composer-phar/51907013#51907013
thanks
In my case an iframe
with a bound src
was trying to get host/null ( when the value of the bound variable was null ).
Adding an *ngIf
to it helped.
I changed:
<iframe [src]="iframeSource"></iframe>
to
<iframe [src]="iframeSource" *ngIf="iframeSource"></iframe>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
new MenuInflater(this).inflate(R.menu.folderview_options, menu);
return (super.onCreateOptionsMenu(menu));
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.locationListRefreshLocations) {
Cursor temp = helper.getEmployee(active_employeeId);
String[] matches = new String[1];
if (temp.moveToFirst()) {
matches[0] = helper.getEmployerID(temp);
}
temp.close();
startRosterReceiveBackgroundTask(matches);
} else if (item.getItemId()==R.id.locationListPrefs) {
startActivity(new Intent(this, PreferencesUnlockScreen.class));
return true;
}
return super.onOptionsItemSelected(item);
}
You have to first obtain the Range object. Also, getCell() will not return the value of the cell but instead will return a Range object of the cell. So, use something on the lines of
function email() {
// Opens SS by its ID
var ss = SpreadsheetApp.openById("0AgJjDgtUl5KddE5rR01NSFcxYTRnUHBCQ0stTXNMenc");
// Get the name of this SS
var name = ss.getName(); // Not necessary
// Read cell 1,1 * Line below does't work *
// var data = Range.getCell(0, 0);
var sheet = ss.getSheetByName('Sheet1'); // or whatever is the name of the sheet
var range = sheet.getRange(1,1);
var data = range.getValue();
}
The hierarchy is Spreadsheet --> Sheet --> Range --> Cell.
Any page you want to perform session-checks on needs to start with:
session_start();
From there, you check your session array for a variable indicating they are logged in:
if (!$_SESSION["loggedIn"]) redirect_to_login();
Logging them in is nothing more than setting that value:
$_SESSION["loggedIn"] = true;
Try format
function:
> xx = 100000000000
> xx
[1] 1e+11
> format(xx, scientific=F)
[1] "100000000000"
If you have an array, then you can find the number of elements in the array by dividing the size of the array in bytes by the size of each element in bytes:
char x[10];
int elements_in_x = sizeof(x) / sizeof(x[0]);
For the specific case of char
, since sizeof(char) == 1
, sizeof(x)
will yield the same result.
If you only have a pointer to an array, then there's no way to find the number of elements in the pointed-to array. You have to keep track of that yourself. For example, given:
char x[10];
char* pointer_to_x = x;
there is no way to tell from just pointer_to_x
that it points to an array of 10 elements. You have to keep track of that information yourself.
There are numerous ways to do that: you can either store the number of elements in a variable or you can encode the contents of the array such that you can get its size somehow by analyzing its contents (this is effectively what null-terminated strings do: they place a '\0'
character at the end of the string so that you know when the string ends).
To create the regex from a string, you have to use JavaScript's RegExp
object.
If you also want to match/replace more than one time, then you must add the g
(global match) flag. Here's an example:
var stringToGoIntoTheRegex = "abc";
var regex = new RegExp("#" + stringToGoIntoTheRegex + "#", "g");
// at this point, the line above is the same as: var regex = /#abc#/g;
var input = "Hello this is #abc# some #abc# stuff.";
var output = input.replace(regex, "!!");
alert(output); // Hello this is !! some !! stuff.
Not every string is a valid regex, though: there are some speciall characters, like (
or [
. To work around this issue, simply escape the string before turning it into a regex. A utility function for that goes in the sample below:
function escapeRegExp(stringToGoIntoTheRegex) {
return stringToGoIntoTheRegex.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
}
var stringToGoIntoTheRegex = escapeRegExp("abc"); // this is the only change from above
var regex = new RegExp("#" + stringToGoIntoTheRegex + "#", "g");
// at this point, the line above is the same as: var regex = /#abc#/g;
var input = "Hello this is #abc# some #abc# stuff.";
var output = input.replace(regex, "!!");
alert(output); // Hello this is !! some !! stuff.
Note: the regex in the question uses the s
modifier, which didn't exist at the time of the question, but does exist -- a s
(dotall) flag/modifier in JavaScript -- today.
chmod a+x
modifies the argument's mode while chmod 755
sets it. Try both variants on something that has full or no permissions and you will notice the difference.
Official Notice: success and error have been deprecated, please use the standard then method instead.
Deprecation Notice: The $http legacy promise methods success and error have been deprecated. Use the standard then method instead. If $httpProvider.useLegacyPromiseExtensions is set to false then these methods will throw $http/legacy error.
link: https://code.angularjs.org/1.5.7/docs/api/ng/service/$http
You can set the index by this code :
sel.selectedIndex = 0;
but remember a caution in this practice, You would not be able to call the server side onclick
method if you select the previous value selected in the drop down..
The Maven manual says to do this:
mvn install:install-file -Dfile=non-maven-proj.jar -DgroupId=some.group -DartifactId=non-maven-proj -Dversion=1 -Dpackaging=jar
Setting export SSL_CERT_FILE=/path/file.crt
should do the job.
I spent ages looking for the answer for a similar problem. It wasn't an issue with the code or the setup, as a very similar code worked perfectly in another .php on the same server. Turned out the problem was caused by a very large amount of data being saved into the session in this page. In one place we had a line like this:$_SESSION['full_list'] = $full_list
where $full_list
was an array of data loaded from the database; each row was an array of about 150 elements. When the code was initially written a couple of years ago, the DB only contained about 1000 rows, so the $full_list
contained about 100 elements, each being an array of about 20 elements. With time, the 20 elements turned into 150 and 1000 rows turned into 17000, so the code was storing close to 64 meg of data into the session. Apparently, with this amount of data being stored, it refused to store anything else. Once we changed the code to deal with data locally without saving it into the session, everything worked perfectly.
For a more detailed answer on creating your own colormaps, I highly suggest visiting this page
If that answer is too much work, you can quickly make your own list of colors and pass them to the color
parameter. All the colormaps are in the cm
matplotlib module. Let's get a list of 30 RGB (plus alpha) color values from the reversed inferno colormap. To do so, first get the colormap and then pass it a sequence of values between 0 and 1. Here, we use np.linspace
to create 30 equally-spaced values between .4 and .8 that represent that portion of the colormap.
from matplotlib import cm
color = cm.inferno_r(np.linspace(.4, .8, 30))
color
array([[ 0.865006, 0.316822, 0.226055, 1. ],
[ 0.851384, 0.30226 , 0.239636, 1. ],
[ 0.832299, 0.283913, 0.257383, 1. ],
[ 0.817341, 0.270954, 0.27039 , 1. ],
[ 0.796607, 0.254728, 0.287264, 1. ],
[ 0.775059, 0.239667, 0.303526, 1. ],
[ 0.758422, 0.229097, 0.315266, 1. ],
[ 0.735683, 0.215906, 0.330245, 1. ],
.....
Then we can use this to plot, using the data from the original post:
import random
x = [{i: random.randint(1, 5)} for i in range(30)]
df = pd.DataFrame(x)
df.plot(kind='bar', stacked=True, color=color, legend=False, figsize=(12, 4))
Just use .empty()
:
// snip...
}).done(function (data) {
// Clear drop down list
$(dropdown).empty(); // <<<<<< No more issue here
// Fill drop down list with new data
$(data).each(function () {
// snip...
There's also a more concise way to build up the options:
// snip...
$(data).each(function () {
$("<option />", {
val: this.value,
text: this.text
}).appendTo(dropdown);
});
For reference I want to add about ExtJS, as explained in Manual: RESTful Web Services. In short, use method to specify GET, POST, PUT, DELETE. Example:
Ext.Ajax.request({
url: '/articles/restful-web-services',
method: 'PUT',
params: {
author: 'Patrick Donelan',
subject: 'RESTful Web Services are easy with Ext!'
}
});
If the Accept header is necessary, it can be set as a default for all requests:
Ext.Ajax.defaultHeaders = {
'Accept': 'application/json'
};
This assumes that the first row of the csv is the headers
import csv
# open the file in universal line ending mode
with open('test.csv', 'rU') as infile:
# read the file as a dictionary for each row ({header : value})
reader = csv.DictReader(infile)
data = {}
for row in reader:
for header, value in row.items():
try:
data[header].append(value)
except KeyError:
data[header] = [value]
# extract the variables you want
names = data['name']
latitude = data['latitude']
longitude = data['longitude']
If you are using Gradle, you can add it as a compile
dependency.
Instructions
Make sure you have the Android Support Repository
SDK package installed. Android Studio automatically recognizes this repository during the build process (not sure about plain IntelliJ).
Add the dependency to {project}/build.gradle
dependencies {
compile 'com.android.support:appcompat-v7:+'
}
Click the Sync Project with Gradle Files
button.
EDIT: Looks like these same instructions are on the documentation under Adding libraries with resources -> Using Android Studio
.
date()
itself is only for formatting, but it accepts a second parameter.
date("F j, Y", time() - 60 * 60 * 24);
To keep it simple I just subtract 24 hours from the unix timestamp.
A modern oop-approach is using DateTime
$date = new DateTime();
$date->sub(new DateInterval('P1D'));
echo $date->format('F j, Y') . "\n";
Or in your case (more readable/obvious)
$date = new DateTime();
$date->add(DateInterval::createFromDateString('yesterday'));
echo $date->format('F j, Y') . "\n";
(Because DateInterval
is negative here, we must add()
it here)
See also: DateTime::sub()
and DateInterval
SHOW ENGINE INNODB STATUS \G
Look for the Section -
TRANSACTIONS
We can use INFORMATION_SCHEMA Tables.
Useful Queries
To check about all the locks transactions are waiting for:
USE INFORMATION_SCHEMA;
SELECT * FROM INNODB_LOCK_WAITS;
A list of blocking transactions:
SELECT *
FROM INNODB_LOCKS
WHERE LOCK_TRX_ID IN (SELECT BLOCKING_TRX_ID FROM INNODB_LOCK_WAITS);
OR
SELECT INNODB_LOCKS.*
FROM INNODB_LOCKS
JOIN INNODB_LOCK_WAITS
ON (INNODB_LOCKS.LOCK_TRX_ID = INNODB_LOCK_WAITS.BLOCKING_TRX_ID);
A List of locks on particular table:
SELECT * FROM INNODB_LOCKS
WHERE LOCK_TABLE = db_name.table_name;
A list of transactions waiting for locks:
SELECT TRX_ID, TRX_REQUESTED_LOCK_ID, TRX_MYSQL_THREAD_ID, TRX_QUERY
FROM INNODB_TRX
WHERE TRX_STATE = 'LOCK WAIT';
Reference - MySQL Troubleshooting: What To Do When Queries Don't Work, Chapter 6 - Page 96.
Is objects
a Linq-To-SQL database context? In which case, you can only use simple expressions to the right of the => operator. The reason is, these expressions are not executed, but are converted to SQL to be executed against the database.
Try this
Arr[] myArray = objects.Select(o => new Obj() {
Var1 = o.someVar,
Var2 = o.var2
}).ToArray();
public static void set(Map<String, String> newenv) throws Exception {
Class[] classes = Collections.class.getDeclaredClasses();
Map<String, String> env = System.getenv();
for(Class cl : classes) {
if("java.util.Collections$UnmodifiableMap".equals(cl.getName())) {
Field field = cl.getDeclaredField("m");
field.setAccessible(true);
Object obj = field.get(env);
Map<String, String> map = (Map<String, String>) obj;
map.clear();
map.putAll(newenv);
}
}
}
Or to add/update a single var and removing the loop as per thejoshwolfe's suggestion.
@SuppressWarnings({ "unchecked" })
public static void updateEnv(String name, String val) throws ReflectiveOperationException {
Map<String, String> env = System.getenv();
Field field = env.getClass().getDeclaredField("m");
field.setAccessible(true);
((Map<String, String>) field.get(env)).put(name, val);
}
I was having this problem as well but following Farhan's lead of using setContentView()
I did just that. using setContentView()
by itself was not enough however. I found that I had to repopulate all of my views with information. To fix this I just pulled all of that code out to another method (I called it build) and in my onCreate
method I just call that build. Now whenever my event occurs that I want my activity to "refresh" I just call build, give it the new information (which I pass in as parameters to build) and I have a refreshed activity.
Version 1:
// Update data of question values with $data from formulay
$Q1 = Question::find($id);
$Q1->fill($data);
$Q1->push();
Version 2:
$Q1 = Question::find($id);
$Q1->field = 'YOUR TEXT OR VALUE';
$Q1->save();
In case of answered question you can use them:
$page = Page::find($id);
$page2update = $page->where('image', $path);
$page2update->image = 'IMGVALUE';
$page2update->save();
I wrote a function wrapper called bar()
for barplot()
to do what you are trying to do here, since I need to do similar things frequently. The Github link to the function is here. After copying and pasting it into R, you do
bar(dv = Species,
factors = c(Category, Reason),
dataframe = Reasonstats,
errbar = FALSE,
ylim=c(0, 140)) #I increased the upper y-limit to accommodate the legend.
The one convenience is that it will put a legend on the plot using the names of the levels in your categorical variable (e.g., "Decline" and "Improved"). If each of your levels has multiple observations, it can also plot the error bars (which does not apply here, hence errbar=FALSE
there's nothing wrong with using CHAR like that..
I think your problem is that you have a space in your tablename. It should be: charteredflight
or chartered_flight
..
Try the following:
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [R,L]
Also, you can also redirect based on port number, for example:
RewriteCond %{SERVER_PORT} ^80$
RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [R=301,L]
This will redirect all requests received on port 80 to HTTPS.
Perhaps your subquery (SELECT ename FROM EMP WHERE empno = mgr)
thinks, give me the employee records that are their own managers! (i.e., where the empno of a row is the same as the mgr of the same row.)
have you considered perhaps rewriting this to use an inner (self) join? (I'm asking, becuase i'm not even sure if the following will work or not.)
SELECT t1.ename, t1.empno, t2.ename as MANAGER, t1.mgr
from emp as t1
inner join emp t2 ON t1.mgr = t2.empno
order by t1.empno;
cache = {}
def fib(n):
if n <= 1:
return n
else:
if n not in cache:
cache[n] = fib(n-1) + fib(n-2)
return cache[n]
Change this line:
model = forest.fit(train_fold, train_y)
to:
model = forest.fit(train_fold, train_y.values.ravel())
Edit:
.values
will give the values in an array. (shape: (n,1)
.ravel
will convert that array shape to (n, )
I think I got it at last by doing some manual transformations with the data before visualization:
d <- diamonds
# computing logarithm of prices
d$price <- log10(d$price)
And work out a formatter to later compute 'back' the logarithmic data:
formatBack <- function(x) 10^x
# or with special formatter (here: "dollar")
formatBack <- function(x) paste(round(10^x, 2), "$", sep=' ')
And draw the plot with given formatter:
m <- ggplot(d, aes(y = price, x = color))
m + geom_boxplot() + scale_y_continuous(formatter='formatBack')
Sorry to the community to bother you with a question I could have solved before! The funny part is: I was working hard to make this plot work a month ago but did not succeed. After asking here, I got it.
Anyway, thanks to @DWin for motivation!
I ended up with a combination of Roberts and chirags answers:
((EditText)findViewById(R.id.search_field)).setOnEditorActionListener(
new EditText.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
// Identifier of the action. This will be either the identifier you supplied,
// or EditorInfo.IME_NULL if being called due to the enter key being pressed.
if (actionId == EditorInfo.IME_ACTION_SEARCH
|| actionId == EditorInfo.IME_ACTION_DONE
|| event.getAction() == KeyEvent.ACTION_DOWN
&& event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
onSearchAction(v);
return true;
}
// Return true if you have consumed the action, else false.
return false;
}
});
Update: The above code would some times activate the callback twice. Instead I've opted for the following code, which I got from the Google chat clients:
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
// If triggered by an enter key, this is the event; otherwise, this is null.
if (event != null) {
// if shift key is down, then we want to insert the '\n' char in the TextView;
// otherwise, the default action is to send the message.
if (!event.isShiftPressed()) {
if (isPreparedForSending()) {
confirmSendMessageIfNeeded();
}
return true;
}
return false;
}
if (isPreparedForSending()) {
confirmSendMessageIfNeeded();
}
return true;
}
Below example may help,
int main(void)
{
double **a2d = new double*[5];
/* initializing Number of rows, in this case 5 rows) */
for (int i = 0; i < 5; i++)
{
a2d[i] = new double[3]; /* initializing Number of columns, in this case 3 columns */
}
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 3; j++)
{
a2d[i][j] = 1; /* Assigning value 1 to all elements */
}
}
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 3; j++)
{
cout << a2d[i][j] << endl; /* Printing all elements to verify all elements have been correctly assigned or not */
}
}
for (int i = 0; i < 5; i++)
delete[] a2d[i];
delete[] a2d;
return 0;
}
I encountered the exact same problem today, Ryan.
In my src (or your root) directory, my log4j.properties file now has the following addition
# https://issues.apache.org/jira/browse/AXIS2-4363
log4j.category.org.apache.axiom=WARN
Thanks for the heads up as to how to do this, Benjamin.
Change RadioGroup group
with CompoundButton buttonView
and then press Ctrl+Shift+O to fix your imports.
If you're behind a proxy, you should use X-Forwarded-For
: http://en.wikipedia.org/wiki/X-Forwarded-For
It is an IETF draft standard with wide support:
The X-Forwarded-For field is supported by most proxy servers, including Squid, Apache mod_proxy, Pound, HAProxy, Varnish cache, IronPort Web Security Appliance, AVANU WebMux, ArrayNetworks, Radware's AppDirector and Alteon ADC, ADC-VX, and ADC-VA, F5 Big-IP, Blue Coat ProxySG, Cisco Cache Engine, McAfee Web Gateway, Phion Airlock, Finjan's Vital Security, NetApp NetCache, jetNEXUS, Crescendo Networks' Maestro, Web Adjuster and Websense Web Security Gateway.
If not, here are a couple other common headers I've seen:
If I understand your problem well you want the following things:
Unfortunately there is no ultimate solution for what you want, but there are some things by which you can make your life easier.
First you should decide one important thing: do you want to store for every version in your project repository a reference to the version of the media files? So for example if you have a project called example.com, do you need know which style.css it used 2 weeks ago, or the latest is always (or mostly) the best?
If you don't need to know that, the solution is easy:
In most of the cases, however, you want to know this versioning information. In this case you have two choices:
Store every project in one big repository. The advantage of this solution is that you will have only 1 copy of the media repository. The big disadvantage is that it is much harder to switch between project versions (if you checkout to a different version you will always modify ALL projects)
Use submodules (as explained in answer 1). This way you will store the media files in one repository, and the projects will contain only a reference to a specific media repo version. But this way you will normally have many local copies of the media repository, and you cannot easily modify a media file in all projects.
If I were you I would probably choose the first or third solution (symbolic links or submodules). If you choose to use submodules you can still do a lot of things to make your life easier:
Before committing you can rename the submodule directory and put a symlink to a common media directory. When you're ready to commit, you can remove the symlink and remove the submodule back, and then commit.
You can add one of your copy of the media repository as a remote repository to all of your projects.
You can add local directories as a remote this way:
cd /my/project2/media
git remote add project1 /my/project1/media
If you modify a file in /my/project1/media, you can commit it and pull it from /my/project2/media without pushing it to a remote server:
cd /my/project1/media
git commit -a -m "message"
cd /my/project2/media
git pull project1 master
You are free to remove these commits later (with git reset) because you haven't shared them with other users.
another important point is that Random.nextInt(n) is repeatable since you can create two Random object with the same seed. This is not possible with Math.random().
You can use:
import random
random.choice(range(n))
or:
random.choice(range(1,n+1))
if you want it from 1
to n
and not from 0
.
It might be easiest to try the RCurl package. Install the package and try the following:
# install.packages("RCurl")
library(RCurl)
URL <- "https://d396qusza40orc.cloudfront.net/getdata%2Fdata%2Fss06hid.csv"
x <- getURL(URL)
## Or
## x <- getURL(URL, ssl.verifypeer = FALSE)
out <- read.csv(textConnection(x))
head(out[1:6])
# RT SERIALNO DIVISION PUMA REGION ST
# 1 H 186 8 700 4 16
# 2 H 306 8 700 4 16
# 3 H 395 8 100 4 16
# 4 H 506 8 700 4 16
# 5 H 835 8 800 4 16
# 6 H 989 8 700 4 16
dim(out)
# [1] 6496 188
download.file("https://d396qusza40orc.cloudfront.net/getdata%2Fdata%2Fss06hid.csv",destfile="reviews.csv",method="libcurl")
You can use strtotime() for time calculation. Here is an example:
$checkTime = strtotime('09:00:59');
echo 'Check Time : '.date('H:i:s', $checkTime);
echo '<hr>';
$loginTime = strtotime('09:01:00');
$diff = $checkTime - $loginTime;
echo 'Login Time : '.date('H:i:s', $loginTime).'<br>';
echo ($diff < 0)? 'Late!' : 'Right time!'; echo '<br>';
echo 'Time diff in sec: '.abs($diff);
echo '<hr>';
$loginTime = strtotime('09:00:59');
$diff = $checkTime - $loginTime;
echo 'Login Time : '.date('H:i:s', $loginTime).'<br>';
echo ($diff < 0)? 'Late!' : 'Right time!';
echo '<hr>';
$loginTime = strtotime('09:00:00');
$diff = $checkTime - $loginTime;
echo 'Login Time : '.date('H:i:s', $loginTime).'<br>';
echo ($diff < 0)? 'Late!' : 'Right time!';
Check the already-asked question - how to get time difference in minutes:
Subtract the past-most one from the future-most one and divide by 60.
Times are done in unix format so they're just a big number showing the number of seconds from January 1 1970 00:00:00 GMT
Set a start page.
When I had this problem, I went into the solution explorer, found the page I wanted to see first (in my case "Home.aspx), right clicked on it and selected "Set As Start Page." This fixed my issue (which sounded really similar to yours). This was in Visual Studio 2012 Professional and I ran it in Firefox.
Also check that you are not using validation groups as that validation wouldnt fire if the validationgroup property was set and not explicitly called via
Page.Validate({Insert validation group name here});
I had this warning when had this in angular.json
config:
"prefix": "app_ng"
When changed to "app"
all worked perfectly fine.
%u prints unsigned integer
%d prints signed integer
to get a pointer address use %p
Here are the full list of formatting escapes. I am just giving a screen shot from this page
If you're using AngularJS, the 'json' filter should do it:
<span>{{someObject | json}}</span>
I did it like this.
$(document).ready(function(){
$("#yourid").click(function(){
$(this).load('@Url.Action("Details")');
});
});
Details Method:
public IActionResult Details()
{
return PartialView("Your Partial View");
}
var d = new Date();
var curr_date = d.getDate();
var curr_month = d.getMonth();
var curr_year = d.getFullYear();
document.write(curr_date + "-" + curr_month + "-" + curr_year);
using this you can format date.
you can change the appearance in the way you want then
for more info you can visit here
var call_to = "http://smart-ip.net/geoip-json?callback=?";
$.getJSON(call_to, function(data){
alert(data.host);
});
data.host
is the ip address. Simply call this from your browser.
http://smart-ip.net/geoip-json?callback=?
[Without quotes] and get the ip.
sometimes something wrong in the syntax of the code inside the function throws this error. Check your function correctly. In my case it happened when I was trying to assign Json fields with values and was using colon : to make the assignment instead of equal sign = ...
The lazy way: simply uninstall from the Windows installation menu (if you're using Windows), or from the rpm command, provided you first re-install it after creating a distribution package.
For example,
python setup.py bdist_wininst
dist/foo-1.0.win32.exe
("foo" being an example of course).
The error comes up when you are trying to assign a list of numpy array of different length to a data frame, and it can be reproduced as follows:
A data frame of four rows:
df = pd.DataFrame({'A': [1,2,3,4]})
Now trying to assign a list/array of two elements to it:
df['B'] = [3,4] # or df['B'] = np.array([3,4])
Both errors out:
ValueError: Length of values does not match length of index
Because the data frame has four rows but the list and array has only two elements.
Work around Solution (use with caution): convert the list/array to a pandas Series, and then when you do assignment, missing index in the Series will be filled with NaN:
df['B'] = pd.Series([3,4])
df
# A B
#0 1 3.0
#1 2 4.0
#2 3 NaN # NaN because the value at index 2 and 3 doesn't exist in the Series
#3 4 NaN
For your specific problem, if you don't care about the index or the correspondence of values between columns, you can reset index for each column after dropping the duplicates:
df.apply(lambda col: col.drop_duplicates().reset_index(drop=True))
# A B
#0 1 1.0
#1 2 5.0
#2 7 9.0
#3 8 NaN
First of all, the place in your code where you are initializing (i.e. assigning for the first time) foo is here:
foo = new ArrayList();
foo is an object (with type List) so it is a reference type, not a value type (like int). As such, it holds a reference to a memory location (e.g. 0xA7D2A834) where your List elements are stored. Lines like this
foo.add("foo"); // Modification-1
do not change the value of foo (which, again, is just a reference to a memory location). Instead, they just add elements into that referenced memory location. To violate the final keyword, you would have to try to re-assign foo as follows again:
foo = new ArrayList();
That would give you a compilation error.
Now, with that out of the way, think about what happens when you add the static keyword.
When you do NOT have the static keyword, each object that instantiates the class has its own copy of foo. Therefore, the constructor assigns a value to a blank, fresh copy of the foo variable, which is perfectly fine.
However, when you DO have the static keyword, only one foo exists in memory that is associated with the class. If you were to create two or more objects, the constructor would be attempting to re-assign that one foo each time, violating the final keyword.
Based on the built-in Powershell examples, this is what Microsoft suggests. Tested and verified:
To stop:
(Get-WmiObject Win32_Service -filter "name='IPEventWatcher'" -ComputerName Server01).StopService()
To start:
(Get-WmiObject Win32_Service -filter "name='IPEventWatcher'" -ComputerName Server01).StartService()
This suffices :
parentGuest.parentNode.insertBefore(childGuest, parentGuest.nextSibling || null);
since if the refnode
(second parameter) is null, a regular appendChild is performed. see here : http://reference.sitepoint.com/javascript/Node/insertBefore
Actually I doubt that the || null
is required, try it and see.
To get the id of the parent div:
$(buttonSelector).parents('div:eq(0)').attr('id');
Also, you can refactor your code quite a bit:
$('button').click( function() {
var correct = Number($(this).attr('rel'));
validate(Number($(this).siblings('input').val()), correct);
$(this).parents('div:eq(0)').html(feedback);
});
Now there is no need for a button-class
explanation
eq(0), means that you will select one element from the jQuery object, in this case element 0, thus the first element. http://docs.jquery.com/Selectors/eq#index
$(selector).siblings(siblingsSelector) will select all siblings (elements with the same parent) that match the siblingsSelector http://docs.jquery.com/Traversing/siblings#expr
$(selector).parents(parentsSelector) will select all parents of the elements matched by selector that match the parent selector. http://docs.jquery.com/Traversing/parents#expr
Thus: $(selector).parents('div:eq(0)'); will match the first parent div of the elements matched by selector.
You should have a look at the jQuery docs, particularly selectors and traversing:
If you add this to your web.config transformation file, you can also set certain publish options to have debugging enabled or disabled:
<system.web>
<customErrors mode="Off" defaultRedirect="~/Error.aspx" xdt:Transform="Replace"/>
</system.web>
If you have an existing list and you want to loop over it and keep track of the indices you can use the enumerate
function. For example
l = ["apple", "pear", "banana"]
for i, fruit in enumerate(l):
print "index", i, "is", fruit
For selecting all in visual: Type Esc to be sure yor are in normal mode
:0
type ENTER to go to the beginning of file
vG
I was getting this error because my cpp files was not added in the CMakeLists.txt file
when I am testing "typeof obj === undefined
", the alert(typeof obj)
returning object
, even though obj is undefined.
Since obj is type of Object
its returning Object
, not undefined
.
So after hours of testing I opted below technique.
if(document.getElementById(obj) !== null){
//do...
}else{
//do...
}
I am not sure why the first technique didn't work.But I get done my work using this.
2014 Edit : The question and this reply are from 2010. At the time, no better solution was widely available. Now, many of the other replies are better : Eric Hu's, or Re Capcha's for example.
This site seems to have a solution for you : jQuery: outerHTML | Yelotofu
jQuery.fn.outerHTML = function(s) {
return s
? this.before(s).remove()
: jQuery("<p>").append(this.eq(0).clone()).html();
};
This macro adds a hyperlink to the worksheet with the same name, I also modify the range to be more flexible, just change the first cell in the code. Works like a charm
Sub hyper()
Dim cl As Range
Dim nS As String
Set MyRange = Sheets("Sheet1").Range("B16")
Set MyRange = Range(MyRange, MyRange.End(xlDown))
For Each cl In MyRange
nS = cl.Value
cl.Hyperlinks.Add Anchor:=cl, Address:="", SubAddress:="'" & nS & "'" & "!B16", TextToDisplay:=nS
Next
End Sub
A very easy way to change the border colour of the stars is using the xml parameter:
android:progressBackgroundTint=""
in the ratingBar view. The value should be a hexadecimal code for a color.
strace supported By Git,as Michael Fox Mention Maybe not useful for complex/windows software.
Since you have created an image from the Dockerfile, the image currently is not in active state. In order to work you need to run this image inside a container.
The $ docker images
command describes how many images are currently available in the local repository.
and
docker ps -a
shows how many containers are currently available, i.e. the list of active and exited containers.
There are two ways to run the image in the container:
$ docker run [OPTIONS] IMAGE[:TAG|@DIGEST] [COMMAND] [ARG...]
In detached mode:
-d=false: Detached mode: Run container in the background, print new container id
In interactive mode:
-i :Keep STDIN open even if not attached
Here is the Docker run command
$ docker run image_name:tag_name
For more clarification on Docker run, you can visit Docker run reference.
It's the best material to understand Docker.
1st way is to use props
<Row id = "someRandomID">
Wherein, in the Definition, you may just go
const Row = props => {
div id = {props.id}
}
The same could be done with class, replacing id with className in the above example.
You might as well use react-html-id
, that is an npm package.
This is an npm package that allows you to use unique html IDs for components without any dependencies on other libraries.
Ref: react-html-id
Peace.
To stick to ==
without consideration of the other type, the following is also possible.
type(a) == type(None)
for file in Data/*.txt
do
for ((i = 0; i < 3; i++))
do
name=${file##*/}
base=${name%.txt}
./MyProgram.exe "$file" Logs/"${base}_Log$i.txt"
done
done
The name=${file##*/}
substitution (shell parameter expansion) removes the leading pathname up to the last /
.
The base=${name%.txt}
substitution removes the trailing .txt
. It's a bit trickier if the extensions can vary.
Use a query terminator string and set this in the options of your SQL client application. I use ; as the query terminator.
Your SQL would look like this;
UPDATE table SET ID = 111111259 WHERE ID = 2555;
UPDATE table SET ID = 111111261 WHERE ID = 2724;
UPDATE table SET ID = 111111263 WHERE ID = 2021;
UPDATE table SET ID = 111111264 WHERE ID = 2017;
This will allow you to do a Ctrl + A and run all the lines at once.
The string terminator tells the SQL client that the update statement is finished and to go to the next line and process the next statement.
Hope that helps
You're using the argument as a reference but actually it's a pointer. Change vector<int>*
to vector<int>&
. And you should really set search4
to something before using it.
Tensorflow upgrade -Python3
>> pip3 install --upgrade tensorflow --user
if you got this
"ERROR: tensorboard 2.0.2 has requirement grpcio>=1.24.3, but you'll have grpcio 1.22.0 which is incompatible."
Upgrade grpcio
>> pip3 install --upgrade grpcio --user
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH);
cal.setTime(sdf.parse("Mon Mar 14 16:02:37 GMT 2011"));// all done
note: set Locale
according to your environment/requirement
See Also
An alternate I would suggest in this use case is to use the MAX(t_stamp) to get the latest row ... e.g.
select t.* from raceway_input_labo t
where t.t_stamp = (select max(t_stamp) from raceway_input_labo)
limit 1
My coding pattern preference (perhaps) - reliable, generally performs at or better than trying to select the 1st row from a sorted list - also the intent is more explicitly readable.
Hope this helps ...
SQLer
The data URI format is:
data:<headers>;<encoding>,<data>
So, you need only append your data to the "data:image/jpeg;," string:
var your_binary_data = document.body.innerText.replace(/(..)/gim,'%$1'); // parse text data to URI format
window.open('data:image/jpeg;,'+your_binary_data);
You can avoid using the --onto parameter by making a temp branch on the commit you like and then use rebase in its simple form:
git branch temp master^
git checkout topic
git rebase temp
git branch -d temp
Okay, so if you don't have LINQ, you could hard-code it:
public int FindMaxAge(List<MyType> list)
{
if (list.Count == 0)
{
throw new InvalidOperationException("Empty list");
}
int maxAge = int.MinValue;
foreach (MyType type in list)
{
if (type.Age > maxAge)
{
maxAge = type.Age;
}
}
return maxAge;
}
Or you could write a more general version, reusable across lots of list types:
public int FindMaxValue<T>(List<T> list, Converter<T, int> projection)
{
if (list.Count == 0)
{
throw new InvalidOperationException("Empty list");
}
int maxValue = int.MinValue;
foreach (T item in list)
{
int value = projection(item);
if (value > maxValue)
{
maxValue = value;
}
}
return maxValue;
}
You can use this with:
// C# 2
int maxAge = FindMaxValue(list, delegate(MyType x) { return x.Age; });
// C# 3
int maxAge = FindMaxValue(list, x => x.Age);
Or you could use LINQBridge :)
In each case, you can return the if block with a simple call to Math.Max
if you want. For example:
foreach (T item in list)
{
maxValue = Math.Max(maxValue, projection(item));
}
download attribute do it
<a class="btn btn-success btn-sm" href="/file_path/file.type" download>
<span>download </span> <i class="fa fa-download"></i>
</a>
A other users suggested,
.empty()
is good enought, because it removes all descendant nodes (both tag-nodes and text-nodes) AND all kind of data stored inside those nodes. See the JQuery's API empty documentation.
If you wish to keep data, like event handlers for example, you should use
.detach()
as described on the JQuery's API detach documentation.
The method .remove() could be usefull for similar purposes.
In my project I use this function for getting huge amount of files. It's pretty fast (put require("FS")
out to make it even faster):
var _getAllFilesFromFolder = function(dir) {
var filesystem = require("fs");
var results = [];
filesystem.readdirSync(dir).forEach(function(file) {
file = dir+'/'+file;
var stat = filesystem.statSync(file);
if (stat && stat.isDirectory()) {
results = results.concat(_getAllFilesFromFolder(file))
} else results.push(file);
});
return results;
};
usage is clear:
_getAllFilesFromFolder(__dirname + "folder");
You actually got it. Just forgot some quotes.
$(this).css({backgroundColor: 'red'});
or
$(this).css('background-color', 'red');
You don't need to pass over a map/object to set only one property. You can just put pass it as string. Note that if passing an object you cannot use a -
. All CSS properties which have such a character are mapped with capital letters.
Reference: .css()
if you commit a wrong file in your last commits follow the instruction :
ISO-8859-1 is a legacy standards from back in 1980s. It can only represent 256 characters so only suitable for some languages in western world. Even for many supported languages, some characters are missing. If you create a text file in this encoding and try copy/paste some Chinese characters, you will see weird results. So in other words, don't use it. Unicode has taken over the world and UTF-8 is pretty much the standards these days unless you have some legacy reasons (like HTTP headers which needs to compatible with everything).
var yourobj={
"c":{
"a":[{"name":"cable - black","value":2},{"name":"case","value":2}]
},
"o":{
"v":[{"name":"over the ear headphones - white/purple","value":1}]
},
"l":{
"e":[{"name":"lens cleaner","value":1}]
},
"h":{
"d":[{"name":"hdmi cable","value":1},
{"name":"hdtv essentials (hdtv cable setup)","value":1},
{"name":"hd dvd \u0026 blue-ray disc lens cleaner","value":1}]
}}
my solution
var obj = [];
for(n1 in yourjson)
for(n1_1 in yourjson[n])
for(n1_2 in yourjson[n][n1_1])
obj[n1_2[name]] = n1_2[value];
Approved code
for(n1 in yourobj){
for(n1_1 in yourobj[n1]){
for(n1_2 in yourobj[n1][n1_1]){
for(n1_3 in yourobj[n1][n1_1][n1_2]){
obj[yourobj[n1][n1_1][n1_2].name]=yourobj[n1][n1_1][n1_2].value;
}
}
}
}
console.log(obj);
result
*You should use distinguish accessorizes when using [] method or dot notation
Personally, I've used this before to build a JSON to POJO converter. In the case that the JSONObject processed with the function contains an array or nested JSONObjects (implying that the data here isn't of a primitive type or String
), I attempt to invoke the setter method using class.cast()
in this fashion:
public static Object convertResponse(Class<?> clazz, JSONObject readResultObject) {
...
for(Method m : clazz.getMethods()) {
if(!m.isAnnotationPresent(convertResultIgnore.class) &&
m.getName().toLowerCase().startsWith("set")) {
...
m.invoke(returnObject, m.getParameters()[0].getClass().cast(convertResponse(m.getParameters()[0].getType(), readResultObject.getJSONObject(key))));
}
...
}
Not sure if this is extremely helpful, but as said here before, reflection is one of the very few legitimate use case of class.cast()
I can think of, at least you have another example now.
You can do it using named-entity recognition (NER). It's fairly simple and there are out-of-the-shelf tools out there to do it, such as spaCy.
NER is an NLP task where a neural network (or other method) is trained to detect certain entities, such as names, places, dates and organizations.
Example:
Sponge Bob went to South beach, he payed a ticket of $200!
I know, Michael is a good person, he goes to McDonalds, but donates to charity at St. Louis street.
Returns:
Just be aware that this is not 100%!
Here are a little snippet for you to try out:
import spacy
phrases = ['Sponge Bob went to South beach, he payed a ticket of $200!', 'I know, Michael is a good person, he goes to McDonalds, but donates to charity at St. Louis street.']
nlp = spacy.load('en')
for phrase in phrases:
doc = nlp(phrase)
replaced = ""
for token in doc:
if token in doc.ents:
replaced+="XXXX "
else:
replaced+=token.text+" "
Read more here: https://spacy.io/usage/linguistic-features#named-entities
You could, instead of replacing with XXXX, replace based on the entity type, like:
if ent.label_ == "PERSON":
replaced += "<PERSON> "
Then:
import re, random
personames = ["Jack", "Mike", "Bob", "Dylan"]
phrase = re.replace("<PERSON>", random.choice(personames), phrase)
I was facing the same error, and look what I was doing. My bad, I was trying to add the same view NativeAdView
to the multiple FrameLayouts
, resolved by creating a separate view NativeAdView
for each FrameLayout
, Thanks
If you want to append instead of replace the output file, you may want to use
dir 1>> files.txt 2>> err.txt
or
dir 1>> files.txt 2>>&1
I guess the below should work (instead of the writer part from your example). I'm unfortunately with no build environment so It's from memory but I hope it helps
using (var fs = File.Open(filePath, FileMode.Open, FileAccess.ReadWrite)))
{
var destinationReader = StreamReader(fs);
var writer = StreamWriter(fs);
while ((line = reader.ReadLine()) != null)
{
if (line_number == line_to_edit)
{
writer.WriteLine(lineToWrite);
}
else
{
destinationReader .ReadLine();
}
line_number++;
}
}
another way is to make a REST call, if you have WebHCat (part of Hive project) installed, is
curl -i http://172.22.123.63:50111/templeton/v1/version/hive?user.name=foo
which will come back with JSON like
{"module":"hive","version":"1.2.1.2.3.0.0-2458"}
WebHCat docs has some details
There's 2 likely reasons that a TaskCanceledException
would be thrown:
Cancel()
on the CancellationTokenSource
associated with the cancellation token before the task completed.HttpClient.Timeout
.My guess is it was a timeout. (If it was an explicit cancellation, you probably would have figured that out.) You can be more certain by inspecting the exception:
try
{
var response = task.Result;
}
catch (TaskCanceledException ex)
{
// Check ex.CancellationToken.IsCancellationRequested here.
// If false, it's pretty safe to assume it was a timeout.
}
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.
You can use the command time /t
for the time and date /t
for the date, here is an example:
@echo off
time /t >%tmp%\time.tmp
date /t >%tmp%\date.tmp
set ttime=<%tmp%\time.tmp
set tdate=<%tmp%\date.tmp
del /f /q %tmp%\time.tmp
del /f /q %tmp%\date.tmp
echo Time: %ttime%
echo Date: %tdate%
pause >nul
You can also use the built in variables %time% and %date%, here is another example:
@echo off
echo Time: %time:~0,5%
echo Date: %date%
pause >nul
Best aproach for me was:
private void grid_receptie_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
int X = 1;
foreach(DataGridViewRow row in grid_receptie.Rows)
{
row.Cells["NR_CRT"].Value = X;
X++;
}
}
In case you are appending to the DOM, make sure the content is compatible:
modal.find ('div.modal-body').append (content) // check content
static void Main(string[] args)
{
HTTPGet req = new HTTPGet();
req.Request("http://checkip.dyndns.org");
string[] a = req.ResponseBody.Split(':');
string a2 = a[1].Substring(1);
string[] a3=a2.Split('<');
string a4 = a3[0];
Console.WriteLine(a4);
Console.ReadLine();
}
Do this small trick with Check IP DNS
Use HTTPGet
class i found on Goldb-Httpget C#
In my case I had special instruction into nginx configuration file:
location ~ \.(js|css|png|jpg|gif|swf|ico|pdf|mov|fla|zip|rar)$ {
try_files $uri =404;
}
All clients have received '404' because nginx nothing known about Flask.
I hope it help someone.
Please keep an eye on the mailing list for problems/solutions discussed by community members. https://groups.google.com/forum/?fromgroups#!forum/angular . It's been really useful to me.
I've got a one liner to make HTML Tables look BootStrapped:
<table class="table table-striped table-bordered table-hover">
The theme suits other controls and it supports alternate row highlighting.
I found the solution for this problem:
My requirements are
AVPlayerViewController
to play videoWhen video is playing, if it's a landscape then allow the screen to rotate landscape right and landscape left. If it's a portrait then lock the view in portrait mode only.
First, define supportedInterfaceOrientationsForWindow
in AppDelegate.swift
var portrait = true
func application(application: UIApplication, supportedInterfaceOrientationsForWindow window: UIWindow?) -> UIInterfaceOrientationMask {
if portrait {
return .Portrait
} else {
return .Landscape
}
}
Second, in your main view controller, define following functions
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
print("\(#function)")
return .Portrait
}
override func preferredInterfaceOrientationForPresentation() -> UIInterfaceOrientation {
return .Portrait
}
override func shouldAutorotate() -> Bool {
return false
}
Then, you need to subclass AVPlayerViewController
class MyPlayerViewController: AVPlayerViewController {
var size: CGSize?
var supportedOrientationMask: UIInterfaceOrientationMask?
var preferredOrientation: UIInterfaceOrientation?
override func viewDidLoad() {
super.viewDidLoad()
if let size = size {
if size.width > size.height {
self.supportedOrientationMask =[.LandscapeLeft,.LandscapeRight]
self.preferredOrientation =.LandscapeRight
} else {
self.supportedOrientationMask =.Portrait
self.preferredOrientation =.Portrait
}
}
}
Override these three functions in MyPlayerViewController.swift
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
return self.supportedOrientationMask!
}
override func preferredInterfaceOrientationForPresentation() -> UIInterfaceOrientation {
return self.preferredOrientation!
}
Because user might rotate device landscape left or landscape right, we need to set auto rotate to be true
override func shouldAutorotate() -> Bool {
return true
}
Finally, create MyPlayerViewController
instance in your view controller and set the property size value.
let playerViewController = MyPlayerViewController()
// Get the thumbnail
let thumbnail = MyAlbumFileManager.sharedManager().getThumbnailFromMyVideoMedia(......)
let size = thumbnail?.size
playerViewController.size = size
Initiate your player with proper videoUrl
, then assign your player to playerViewController
. Happy coding!
The short answer is adding a class directly to the element you want to style is indeed the most efficient way to target and style that Element. BUT, in real world scenarios it is so negligible that it is not an issue at all to worry about.
To quote Steve Ouders (CSS optimization expert) http://www.stevesouders.com/blog/2009/03/10/performance-impact-of-css-selectors/:
Based on tests I have the following hypothesis: For most web sites, the possible performance gains from optimizing CSS selectors will be small, and are not worth the costs.
Maintainability of code is much more important in real world scenarios. Since the underlying topic here is front-end performance; the real performance boosters for speedy page rendering are found in:
Source: http://stevesouders.com/docs/web20expo-20090402.ppt
So just to confirm, the answer is yes, example below is indeed faster but be aware of the bigger picture:
<div class="column">
<img class="custom-style" alt="appropriate alt text" />
</div>
If you're actually building a real system, then yes, you'd typically just use the stuff in the standard library if what you need is available there. That said, don't think of this as a pointless exercise. It's good to understand how things work, and understanding linked lists is an important step towards understanding more complex data structures, many of which don't exist in the standard libraries.
There are some differences between the way you're creating a linked list and the way the Java collections API does it. The Collections API is trying to adhere to a more complicated interface. The Collections API linked list is also a doubly linked list, while you're building a singly linked list. What you're doing is more appropriate for a class assignment.
With your LinkedList
class, an instance will always be a list of at least one element. With this kind of setup you'd use null
for when you need an empty list.
Think of next
as being "the rest of the list". In fact, many similar implementations use the name "tail" instead of "next".
Here's a diagram of a LinkedList
containing 3 elements:
Note that it's a LinkedList
object pointing to a word ("Hello") and a list of 2 elements. The list of 2 elements has a word ("Stack") and a list of 1 element. That list of 1 element has a word ("Overflow") and an empty list (null
). So you can treat next
as just another list that happens to be one element shorter.
You may want to add another constructor that just takes a String, and sets next to null
. This would be for creating a 1-element list.
To append, you check if next
is null
. If it is, create a new one element list and set next
to that.
next = new LinkedList(word);
If next isn't null
, then append to next
instead.
next.append(word);
This is the recursive approach, which is the least amount of code. You can turn that into an iterative solution which would be more efficient in Java*, and wouldn't risk a stack overflow with very long lists, but I'm guessing that level of complexity isn't needed for your assignment.
* Some languages have tail call elimination, which is an optimization that lets the language implementation convert "tail calls" (a call to another function as the very last step before returning) into (effectively) a "goto". This makes such code completely avoid using the stack, which makes it safer (you can't overflow the stack if you don't use the stack) and typically more efficient. Scheme is probably the most well known example of a language with this feature.
If dgv(11, dgv.CurrentRow.Index).Selected = True Then
dgv.Rows.RemoveAt(dgv.CurrentRow.Index)
Else
Exit Sub
End If
This is similar to the solution referred by Mark Heath but with not as much code to just create a very basic button, without the built-in mouse over animation effect. It preserves a simple mouse over effect of showing the button border in black.
The style can be inserted into the Window.Resources or UserControl.Resources section for example (as shown).
<UserControl.Resources>
<!-- This style is used for buttons, to remove the WPF default 'animated' mouse over effect -->
<Style x:Key="MyButtonStyle" TargetType="Button">
<Setter Property="OverridesDefaultStyle" Value="True"/>
<Setter Property="Margin" Value="5"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Border Name="border"
BorderThickness="1"
Padding="4,2"
BorderBrush="DarkGray"
CornerRadius="3"
Background="{TemplateBinding Background}">
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="border" Property="BorderBrush" Value="Black" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</UserControl.Resources>
<!-- usage in xaml -->
<Button Style="{StaticResource MyButtonStyle}">Hello!</Button>
You just need to install Android development kit from http://developer.android.com/sdk/installing/studio.html#Updating
and also Download and install Java JDK (Choose the Java platform)
define the environment variable in windows System setting https://confluence.atlassian.com/display/DOC/Setting+the+JAVA_HOME+Variable+in+Windows
Voila ! You are Donezo !
make sure """ comments are only a tab away and not 5 spaces
if you are planning to run it from a separate sql file. here is a good example (taken from a great page to learn how to bash with postgresql http://www.manniwood.com/postgresql_and_bash_stuff/index.html
#!/bin/bash
set -e
set -u
if [ $# != 2 ]; then
echo "please enter a db host and a table suffix"
exit 1
fi
export DBHOST=$1
export TSUFF=$2
psql \
-X \
-U user \
-h $DBHOST \
-f /path/to/sql/file.sql \
--echo-all \
--set AUTOCOMMIT=off \
--set ON_ERROR_STOP=on \
--set TSUFF=$TSUFF \
--set QTSTUFF=\'$TSUFF\' \
mydatabase
psql_exit_status = $?
if [ $psql_exit_status != 0 ]; then
echo "psql failed while trying to run this sql script" 1>&2
exit $psql_exit_status
fi
echo "sql script successful"
exit 0
I get a better result setting this class:
.modal-dialog {
position: absolute;
top: 50px;
right: 100px;
bottom: 0;
left: 0;
z-index: 10040;
overflow: auto;
overflow-y: auto;
}
With bootstrap 3.3.7.
(all credits to msnfreaky for the idea...)
The commands dict.items()
, dict.keys()
and dict.values()
return a copy of the dictionary's list of (k, v)
pair, keys and values.
This could take a lot of memory if the copied list is very large.
The commands dict.iteritems()
, dict.iterkeys()
and dict.itervalues()
return an iterator over the dictionary’s (k, v)
pair, keys and values.
The commands dict.viewitems()
, dict.viewkeys()
and dict.viewvalues()
return the view objects, which can reflect the dictionary's changes.
(I.e. if you del
an item or add a (k,v)
pair in the dictionary, the view object can automatically change at the same time.)
$ python2.7
>>> d = {'one':1, 'two':2}
>>> type(d.items())
<type 'list'>
>>> type(d.keys())
<type 'list'>
>>>
>>>
>>> type(d.iteritems())
<type 'dictionary-itemiterator'>
>>> type(d.iterkeys())
<type 'dictionary-keyiterator'>
>>>
>>>
>>> type(d.viewitems())
<type 'dict_items'>
>>> type(d.viewkeys())
<type 'dict_keys'>
In Py3.x, things are more clean, since there are only dict.items()
, dict.keys()
and dict.values()
available, which return the view objects just as dict.viewitems()
in Py2.x did.
Just as @lvc noted, view object isn't the same as iterator, so if you want to return an iterator in Py3.x, you could use iter(dictview)
:
$ python3.3
>>> d = {'one':'1', 'two':'2'}
>>> type(d.items())
<class 'dict_items'>
>>>
>>> type(d.keys())
<class 'dict_keys'>
>>>
>>>
>>> ii = iter(d.items())
>>> type(ii)
<class 'dict_itemiterator'>
>>>
>>> ik = iter(d.keys())
>>> type(ik)
<class 'dict_keyiterator'>
The problem is that they're all the same exact list in memory. When you use the [x]*n
syntax, what you get is a list of n
many x
objects, but they're all references to the same object. They're not distinct instances, rather, just n
references to the same instance.
To make a list of 3 different lists, do this:
x = [[] for i in range(3)]
This gives you 3 separate instances of []
, which is what you want
[[]]*n
is similar to
l = []
x = []
for i in range(n):
x.append(l)
While [[] for i in range(3)]
is similar to:
x = []
for i in range(n):
x.append([]) # appending a new list!
In [20]: x = [[]] * 4
In [21]: [id(i) for i in x]
Out[21]: [164363948, 164363948, 164363948, 164363948] # same id()'s for each list,i.e same object
In [22]: x=[[] for i in range(4)]
In [23]: [id(i) for i in x]
Out[23]: [164382060, 164364140, 164363628, 164381292] #different id(), i.e unique objects this time
The scaling on your example figure is a bit strange but you can force it by plotting the index of each x-value and then setting the ticks to the data points:
import matplotlib.pyplot as plt
x = [0.00001,0.001,0.01,0.1,0.5,1,5]
# create an index for each tick position
xi = list(range(len(x)))
y = [0.945,0.885,0.893,0.9,0.996,1.25,1.19]
plt.ylim(0.8,1.4)
# plot the index for the x-values
plt.plot(xi, y, marker='o', linestyle='--', color='r', label='Square')
plt.xlabel('x')
plt.ylabel('y')
plt.xticks(xi, x)
plt.title('compare')
plt.legend()
plt.show()
This problem is probably from your /etc/apt/sources.list as others mentioned but there is chance that the problem is with your hard disk. I solved the same issue by cleaning up some space.
When you don't have enough space on your hard disk, updating your machine won't occur until you delete some files.
This might be what you are looking for:
yourStream
.filter(/* your criteria */)
.findFirst()
.get();
And better, if there's a possibility of matching no element, in which case get()
will throw a NPE. So use:
yourStream
.filter(/* your criteria */)
.findFirst()
.orElse(null); /* You could also create a default object here */
public static void main(String[] args) {
class Stop {
private final String stationName;
private final int passengerCount;
Stop(final String stationName, final int passengerCount) {
this.stationName = stationName;
this.passengerCount = passengerCount;
}
}
List<Stop> stops = new LinkedList<>();
stops.add(new Stop("Station1", 250));
stops.add(new Stop("Station2", 275));
stops.add(new Stop("Station3", 390));
stops.add(new Stop("Station2", 210));
stops.add(new Stop("Station1", 190));
Stop firstStopAtStation1 = stops.stream()
.filter(e -> e.stationName.equals("Station1"))
.findFirst()
.orElse(null);
System.out.printf("At the first stop at Station1 there were %d passengers in the train.", firstStopAtStation1.passengerCount);
}
Output is:
At the first stop at Station1 there were 250 passengers in the train.
In short, no, you can't.
Long answer, extension methods are just syntactic sugar. IE:
If you have an extension method on string let's say:
public static string SomeStringExtension(this string s)
{
//whatever..
}
When you then call it:
myString.SomeStringExtension();
The compiler just turns it into:
ExtensionClass.SomeStringExtension(myString);
So as you can see, there's no way to do that for static methods.
And another thing just dawned on me: what would really be the point of being able to add static methods on existing classes? You can just have your own helper class that does the same thing, so what's really the benefit in being able to do:
Bool.Parse(..)
vs.
Helper.ParseBool(..);
Doesn't really bring much to the table...
I know I'm very late but for those who still have that problem, it can be solved easily. I use Qt 5.3 and it works fine. No need to create a function or all that.
int valueComboBox;
valueComboBox = comboBox->currentIndex();
and it works ! Hope it helps !
This all depends on what sort of access you have to your SAP system. An ABAP program that exports the data and/or an RFC that your macro can call to directly get the data or have SAP create the file is probably best.
However as a general rule people looking for this sort of answer are looking for an immediate solution that does not require their IT department to spend months customizing their SAP system.
In that case you probably want to use SAP GUI Scripting. SAP GUI scripting allows you to automate the Windows SAP GUI in much the same way as you automate Excel. In fact you can call the SAP GUI directly from an Excel macro. Read up more on it here. The SAP GUI has a macro recording tool much like Excel does. It records macros in VBScript which is nearly identical to Excel VBA and can usually be copied and pasted into an Excel macro directly.
Here is a simple example based on a SAP system I have access to.
Public Sub SimpleSAPExport()
Set SapGuiAuto = GetObject("SAPGUI") 'Get the SAP GUI Scripting object
Set SAPApp = SapGuiAuto.GetScriptingEngine 'Get the currently running SAP GUI
Set SAPCon = SAPApp.Children(0) 'Get the first system that is currently connected
Set session = SAPCon.Children(0) 'Get the first session (window) on that connection
'Start the transaction to view a table
session.StartTransaction "SE16"
'Select table T001
session.findById("wnd[0]/usr/ctxtDATABROWSE-TABLENAME").Text = "T001"
session.findById("wnd[0]/tbar[1]/btn[7]").Press
'Set our selection criteria
session.findById("wnd[0]/usr/txtMAX_SEL").text = "2"
session.findById("wnd[0]/tbar[1]/btn[8]").press
'Click the export to file button
session.findById("wnd[0]/tbar[1]/btn[45]").press
'Choose the export format
session.findById("wnd[1]/usr/subSUBSCREEN_STEPLOOP:SAPLSPO5:0150/sub:SAPLSPO5:0150/radSPOPLI-SELFLAG[1,0]").select
session.findById("wnd[1]/tbar[0]/btn[0]").press
'Choose the export filename
session.findById("wnd[1]/usr/ctxtDY_FILENAME").text = "test.txt"
session.findById("wnd[1]/usr/ctxtDY_PATH").text = "C:\Temp\"
'Export the file
session.findById("wnd[1]/tbar[0]/btn[0]").press
End Sub
To help find the names of elements such aswnd[1]/tbar[0]/btn[0]
you can use script recording.
Click the customize local layout button, it probably looks a bit like this:
Then find the Script Recording and Playback menu item.
Within that the More
button allows you to see/change the file that the VB Script is recorded to. The output format is a bit messy, it records things like selecting text, clicking inside a text field, etc.
The provided script should work if copied directly into a VBA macro. It uses late binding, the line Set SapGuiAuto = GetObject("SAPGUI")
defines the SapGuiAuto object.
If however you want to use early binding so that your VBA editor might show the properties and methods of the objects you are using, you need to add a reference to sapfewse.ocx
in the SAP GUI installation folder.
Why think? If not
confuses you, switch your if and else clauses around to avoid the negation.
i want to make sure that ( u0 <= u < u0+step ) before do sth.
Just write that.
if u0 <= u < u0+step:
"do sth" # What language is "sth"? No vowels. An odd-looking word.
else:
u0 = u0+ step
Why overthink it?
If you need an empty if
-- and can't work out the logic -- use pass
.
if some-condition-that's-too-complex-for-me-to-invert:
pass
else:
do real work here
Solved the problem by re-installing CUDA:
wget https://developer.download.nvidia.com/compute/cuda/repos/ubuntu1804/x86_64/cuda-ubuntu1804.pin
mv cuda-ubuntu1804.pin /etc/apt/preferences.d/cuda-repository-pin-600
wget https://developer.download.nvidia.com/compute/cuda/11.1.0/local_installers/cuda-repo-ubuntu1804-11-1-local_11.1.0-455.23.05-1_amd64.deb
echo "md5sum: $(md5sum cuda-repo-ubuntu1804-11-1-local_11.1.0-455.23.05-1_amd64.deb)"
echo "correct: 056de5e03444cce506202f50967b0016"
dpkg -i cuda-repo-ubuntu1804-11-1-local_11.1.0-455.23.05-1_amd64.deb
apt-key add /var/cuda-repo-ubuntu1804-11-1-local/7fa2af80.pub
apt-get -qq update
apt-get -qq -y install cuda
rm cuda-repo-ubuntu1804-11-1-local_11.1.0-455.23.05-1_amd64.deb
And for negatives values:
Public Function IsBetween(Of T)(item As T, pStart As T, pEnd As T) As Boolean ' https://msdn.microsoft.com/fr-fr/library/bb384936.aspx
Dim Deb As T = pStart
Dim Fin As T = pEnd
If (Comparer(Of T).Default.Compare(pStart, pEnd) > 0) Then Deb = pEnd : Fin = pStart
Return Comparer(Of T).Default.Compare(item, Deb) >= 0 AndAlso Comparer(Of T).Default.Compare(item, Fin) <= 0
End Function
I would avoid inline javascript altogether, and as I mentioned in my comment, I'd also probably use <input type="button" />
for this. That being said...
<a href="http://stackoverflow.com/questions/16337937/how-to-call-javascript-from-a-href" id="mylink">Link.</a>
var clickHandler = function() {
alert('Stuff happens now.');
}
if (document.addEventListener) {
document.getElementById('mylink').addEventListener('click', clickHandler, false);
} else {
document.getElementById('mylink').attachEvent('click', clickHandler);
}
API Sanity Checker — test framework for C/C++ libraries:
An automatic generator of basic unit tests for a shared C/C++ library. It is able to generate reasonable (in most, but unfortunately not all, cases) input data for parameters and compose simple ("sanity" or "shallow"-quality) test cases for every function in the API through the analysis of declarations in header files.
The quality of generated tests allows to check absence of critical errors in simple use cases. The tool is able to build and execute generated tests and detect crashes (segfaults), aborts, all kinds of emitted signals, non-zero program return code and program hanging.
Unique features in comparison with CppUnit, Boost and Google Test:
In case you are using node.js (with express)
If you want to serve static files in node.js, you need to use a function. Add the following code to your js file:
app.use(express.static("public"));
Where app is:
const express = require("express");
const app = express();
Then create a folder called public in you project folder. (You could call it something else, this is just good practice but remember to change it from the function as well.)
Then in this file create another folder named css (and/or images file under css if you want to serve static images as well.) then add your css files to this folder.
After you add them change the stylesheet accordingly. For example if it was:
href="cssFileName.css"
and
src="imgName.png"
Make them:
href="css/cssFileName.css"
src="css/images/imgName.png"
That should work
Let's assume you have a class like this:
public class Staff
{
public int ID { get; set; }
public string Name { get; set; }
}
And assume you have dragged and dropped a DataGridView
to your form, and name it dataGridView1.
You need a BindingSource to hold your data to bind your DataGridView
. This is how you can do it:
private void frmDGV_Load(object sender, EventArgs e)
{
//dummy data
List<Staff> lstStaff = new List<Staff>();
lstStaff.Add(new Staff()
{
ID = 1,
Name = "XX"
});
lstStaff.Add(new Staff()
{
ID = 2,
Name = "YY"
});
//use binding source to hold dummy data
BindingSource binding = new BindingSource();
binding.DataSource = lstStaff;
//bind datagridview to binding source
dataGridView1.DataSource = binding;
}
I did not find the answer to my question after searching Google & stackoverflow for a while so I would like to share my solution here.
git config --global credential.helper "/bin/bash /git_creds.sh"
echo '#!/bin/bash' > /git_creds.sh
echo "sleep 1" >> /git_creds.sh
echo "echo username=$SERVICE_USER" >> /git_creds.sh
echo "echo password=$SERVICE_PASS" >> /git_creds.sh
# to test it
git clone https://my-scm-provider.com/project.git
I did it for Windows too. Full answer here
You can use any bash looping constructs like FOR
, with is compatible to Linux and Mac.
https://tiswww.case.edu/php/chet/bash/bashref.html#Looping-Constructs
In your specific case you can define N
iterations, with N
is a number defining how many curl
executions you want.
for n in {1..N}; do curl <arguments>; done
ex:
for n in {1..20}; do curl -d @notification.json -H 'Content-Type: application/json' localhost:3000/dispatcher/notify; done
Anonymous ftp logins are usually the username 'anonymous' with the user's email address as the password. Some servers parse the password to ensure it looks like an email address.
User: anonymous
Password: [email protected]
You can get it like
[ x[0] for x in a]
which will return a list of the first element of each list in a
Use svn revert --recursive folder_name
svn revert
is inherently dangerous, since its entire purpose is to throw away data — namely, your uncommitted changes. Once you've reverted, Subversion provides no way to get back those uncommitted changes.
http://svnbook.red-bean.com/en/1.7/svn.ref.svn.c.revert.html
js-xlsx library makes it easy to convert Excel/CSV files into JSON objects.
Download the xlsx.full.min.js file from here. Write below code on your HTML page Edit the referenced js file link (xlsx.full.min.js) and link of Excel file
<!doctype html>
<html>
<head>
<title>Excel to JSON Demo</title>
<script src="xlsx.full.min.js"></script>
</head>
<body>
<script>
/* set up XMLHttpRequest */
var url = "http://myclassbook.org/wp-content/uploads/2017/12/Test.xlsx";
var oReq = new XMLHttpRequest();
oReq.open("GET", url, true);
oReq.responseType = "arraybuffer";
oReq.onload = function(e) {
var arraybuffer = oReq.response;
/* convert data to binary string */
var data = new Uint8Array(arraybuffer);
var arr = new Array();
for (var i = 0; i != data.length; ++i) arr[i] = String.fromCharCode(data[i]);
var bstr = arr.join("");
/* Call XLSX */
var workbook = XLSX.read(bstr, {
type: "binary"
});
/* DO SOMETHING WITH workbook HERE */
var first_sheet_name = workbook.SheetNames[0];
/* Get worksheet */
var worksheet = workbook.Sheets[first_sheet_name];
console.log(XLSX.utils.sheet_to_json(worksheet, {
raw: true
}));
}
oReq.send();
</script>
</body>
</html>
Input:
Output:
If you want to use hex codes, you should add -e
option to enable interpretation of backslash escapes by echo (but the result is the same as with echo
CtrlRCtrlB). And as wallyk said, you probably want to add -n
to prevent the output of a newline:
echo -en '\x12\x02' > /dev/ttyS0
Also make sure that /dev/ttyS0
is the port you want.
public static class MyExtension
{
public static string ToPrettySize(this float Size)
{
return ConvertToPrettySize(Size, 0);
}
public static string ToPrettySize(this int Size)
{
return ConvertToPrettySize(Size, 0);
}
private static string ConvertToPrettySize(float Size, int R)
{
float F = Size / 1024f;
if (F < 1)
{
switch (R)
{
case 0:
return string.Format("{0:0.00} byte", Size);
case 1:
return string.Format("{0:0.00} kb", Size);
case 2:
return string.Format("{0:0.00} mb", Size);
case 3:
return string.Format("{0:0.00} gb", Size);
}
}
return ConvertToPrettySize(F, ++R);
}
}
Try using this library: https://github.com/jakiestfu/Blur.js-II
That should do it for ya.
You might want to run python manage.py collectstatic
after you set DEBUG = False
and ALLOWED_HOSTS = ['127.0.0.1']
in settings.py
. After these two steps my web application ran well in my local server even with DEBUG=False mode.
BTW I have these settings in settings.py
.
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware', # what i added
'django.middleware.common.CommonMiddleware', # and so on...
]
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
I assume maybe whitenoise setting has something to do with collectstatic command.
It's a long time since the question was posted, but I experienced the same issue in a similar scenario. I have a console application and I was consuming a web service and our IIS server where the webservice was placed has windows authentication (NTLM) enabled.
I followed this link and that fixed my problem. Here's the sample code for App.config
:
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="Service1Soap">
<security mode="TransportCredentialOnly">
<transport clientCredentialType="Ntlm" proxyCredentialType="None"
realm=""/>
<message clientCredentialType="UserName" algorithmSuite="Default"/>
</security>
</binding>
</basicHttpBinding>
</bindings>
<client>
<endpoint address="http://localhost/servicename/service1.asmx"
binding="basicHttpBinding" bindingConfiguration="ListsSoap"/>
</client>
</system.serviceModel>
Guid.TryParse()
https://msdn.microsoft.com/de-de/library/system.guid.tryparse(v=vs.110).aspx
or
Guid.TryParseExact()
https://msdn.microsoft.com/de-de/library/system.guid.tryparseexact(v=vs.110).aspx
in .NET 4.0 (or 3.5?)