For a custom class to work properly in collections you'll have to implement/override the equals()
methods of the class. For sorting also override compareTo()
.
See this article or google about how to implement those methods properly.
Basically it contains all the attributes which describe the object in question. It can be used to alter or read the attributes.
Quoting from the documentation for __dict__
A dictionary or other mapping object used to store an object's (writable) attributes.
Remember, everything is an object in Python. When I say everything, I mean everything like functions, classes, objects etc (Ya you read it right, classes. Classes are also objects). For example:
def func():
pass
func.temp = 1
print(func.__dict__)
class TempClass:
a = 1
def temp_function(self):
pass
print(TempClass.__dict__)
will output
{'temp': 1}
{'__module__': '__main__',
'a': 1,
'temp_function': <function TempClass.temp_function at 0x10a3a2950>,
'__dict__': <attribute '__dict__' of 'TempClass' objects>,
'__weakref__': <attribute '__weakref__' of 'TempClass' objects>,
'__doc__': None}
There's a working JSFiddle with a small example here, that demonstrates exactly what you are looking for (unless I've misunderstood your request): http://jsfiddle.net/9N7Z2/188/
There are a few issues with that method of loading javascript dynamically. When it comes to the very basal frameworks, like jQuery, you actually probably want to load them statically, because otherwise, you would have to write a whole JavaScript loading framework...
You could use some of the existing JavaScript loaders, or write your own by watching for window.jQuery
to get defined.
// Immediately-invoked function expression
(function() {
// Load the script
var script = document.createElement("SCRIPT");
script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js';
script.type = 'text/javascript';
script.onload = function() {
var $ = window.jQuery;
// Use $ here...
};
document.getElementsByTagName("head")[0].appendChild(script);
})();
Just remember that if you need to support really old browsers, like IE8, load
event handlers do not execute. In that case, you would need to poll for the existance of window.jQuery
using repeated window.setTimeout
. There is a working JSFiddle with that method here: http://jsfiddle.net/9N7Z2/3/
There are lots of people who have already done what you need to do. Check out some of the existing JavaScript Loader frameworks, like:
#applyCSS > * {
/* Your style */
}
Check this JSfiddle
It will style all children and grandchildren, but will exclude loosely flying text in the div itself and only target wrapped (by tags) content.
The content inside strings in Golang can be compared using ==
operator. If the results are not as expected there may be some hidden characters like \n
, \r
, spaces, etc. So as a general rule of thumb, try removing those using functions provided by strings
package in golang.
For Instance, spaces can be removed using strings.TrimSpace
function. You can also define a custom function to remove any character you need. strings.TrimFunc
function can give you more power.
Sometimes it is just a matter of closing Visual Studio 2015 and then open again.
Update: Visual Studio 2017 apparently as well.
I have had this happen on a few machines.
This does happen.
"Have you tried to delete the "Your_Solution_FileName.suo" file?"
Also computer crashing like e.g. power outage etc...
Applies to Update 2 and Update 3 as well as fresh base without any updates...
<div class="container">
<h1>About me</h1>
<div class="row">
<div class="pull-left ">
<img src="http://lorempixel.com/200/200" class="col-lg-3" class="img- responsive" alt="Responsive image">
<p class="col-md-4">Lots of text here... </p>
</div>
</div>
</div>
</div>
$('body').on('hidden.bs.modal', '.modal', function () {
$("#mention Id here what you showed inside modal body").empty()
});
Which html element you want to empty like(div,span whatever).
datetime.datetime.now() - datetime.timedelta(0, 15 * 60)
timedelta
is a "change in time". It takes days as the first parameter and seconds in the second parameter. 15 * 60
seconds is 15 minutes.
You can either
1) Declare printMenu()
, getUserchoice()
and input as static
OR
2) If you want to design it better, move the logic from your main
into a separate instance method. And then from the main
create a new instance of your class and call your instance method(s)
You can find more methods and functions related to Python strings in section 5.6.1. String Methods of the documentation.
w.strip(',.').lower()
I agree with Justin. To elaborate, overly long lines of code are harder to read by humans and some people might have console widths that only accommodate 80 characters per line.
The style recommendation is there to ensure that the code you write can be read by as many people as possible on as many platforms as possible and as comfortably as possible.
Use json_decode($json_string, TRUE)
function to convert the JSON object to an array.
Example:
$json_string = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
$my_array_data = json_decode($json_string, TRUE);
NOTE: The second parameter will convert decoded JSON string into an associative array.
===========
Output:
var_dump($my_array_data);
array(5) {
["a"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)
}
Underscore-java can build hashmap.
Map<String, Object> value = U.objectBuilder()
.add("firstName", "John")
.add("lastName", "Smith")
.add("age", 25)
.add("address", U.arrayBuilder()
.add(U.objectBuilder()
.add("streetAddress", "21 2nd Street")
.add("city", "New York")
.add("state", "NY")
.add("postalCode", "10021")))
.add("phoneNumber", U.arrayBuilder()
.add(U.objectBuilder()
.add("type", "home")
.add("number", "212 555-1234"))
.add(U.objectBuilder()
.add("type", "fax")
.add("number", "646 555-4567")))
.build();
// {firstName=John, lastName=Smith, age=25, address=[{streetAddress=21 2nd Street,
// city=New York, state=NY, postalCode=10021}], phoneNumber=[{type=home, number=212 555-1234},
// {type=fax, number=646 555-4567}]}
Sort of solution using metatable...
local function preparetable(t)
setmetatable(t,{__newindex=function(self,k,v) rawset(self,v,true) end})
end
local workingtable={}
preparetable(workingtable)
table.insert(workingtable,123)
table.insert(workingtable,456)
if workingtable[456] then
...
end
Assuming thant the content of mandrill_events
is an object (not a string), you can also use shift()
function:
var req = { mandrill_events: [{"event":"inbound","ts":1426249238}] };
var event-property = req.mandrill_events.shift().event;
You can access the MySQL command line with XAMPP for Windows
click XAMPP icon to launch its cPanel
click on Shell button
mysql -h localhost -u root
and click enterYou should see all the command lines and what they do
Setting environment for using XAMPP for Windows.
Your PC c:\xampp
# mysql -h localhost - root
mysql Ver 15.1 Distrib 10.1.19-MariaDB, for Win32 (AMD64)
Copyright (c) 2000, 2016, Oracle, MariaDB Corporation Ab and others.
Usage: mysql [OPTIONS] [database]
Default options are read from the following files in the given order:
C:\WINDOWS\my.ini C:\WINDOWS\my.cnf C:\my.ini C:\my.cnf C:\xampp\mysql\my.ini C:\xampp\mysql\my.cnf C:\xampp\mysql\bin\my.ini C:\xampp\mysql\bin\my.cnf
The following groups are read: mysql client client-server client-mariadb
The following options may be given as the first argument:
--print-defaults Print the program argument list and exit.
--no-defaults Don't read default options from any option file.
--defaults-file=# Only read default options from the given file #.
--defaults-extra-file=# Read this file after the global files are read.
-?, --help Display this help and exit.
-I, --help Synonym for -?
--abort-source-on-error
Abort 'source filename' operations in case of errors
--auto-rehash Enable automatic rehashing. One doesn't need to use
'rehash' to get table and field completion, but startup
and reconnecting may take a longer time. Disable with
--disable-auto-rehash.
(Defaults to on; use --skip-auto-rehash to disable.)
-A, --no-auto-rehash
No automatic rehashing. One has to use 'rehash' to get
table and field completion. This gives a quicker start of
mysql and disables rehashing on reconnect.
--auto-vertical-output
Automatically switch to vertical output mode if the
result is wider than the terminal width.
-B, --batch Don't use history file. Disable interactive behavior.
(Enables --silent.)
--character-sets-dir=name
Directory for character set files.
--column-type-info Display column type information.
-c, --comments Preserve comments. Send comments to the server. The
default is --skip-comments (discard comments), enable
with --comments.
-C, --compress Use compression in server/client protocol.
-#, --debug[=#] This is a non-debug version. Catch this and exit.
--debug-check Check memory and open file usage at exit.
-T, --debug-info Print some debug info at exit.
-D, --database=name Database to use.
--default-character-set=name
Set the default character set.
--delimiter=name Delimiter to be used.
-e, --execute=name Execute command and quit. (Disables --force and history
file.)
-E, --vertical Print the output of a query (rows) vertically.
-f, --force Continue even if we get an SQL error. Sets
abort-source-on-error to 0
-G, --named-commands
Enable named commands. Named commands mean this program's
internal commands; see mysql> help . When enabled, the
named commands can be used from any line of the query,
otherwise only from the first line, before an enter.
Disable with --disable-named-commands. This option is
disabled by default.
-i, --ignore-spaces Ignore space after function names.
--init-command=name SQL Command to execute when connecting to MySQL server.
Will automatically be re-executed when reconnecting.
--local-infile Enable/disable LOAD DATA LOCAL INFILE.
-b, --no-beep Turn off beep on error.
-h, --host=name Connect to host.
-H, --html Produce HTML output.
-X, --xml Produce XML output.
--line-numbers Write line numbers for errors.
(Defaults to on; use --skip-line-numbers to disable.)
-L, --skip-line-numbers
Don't write line number for errors.
-n, --unbuffered Flush buffer after each query.
--column-names Write column names in results.
(Defaults to on; use --skip-column-names to disable.)
-N, --skip-column-names
Don't write column names in results.
--sigint-ignore Ignore SIGINT (CTRL-C).
-o, --one-database Ignore statements except those that occur while the
default database is the one named at the command line.
-p, --password[=name]
Password to use when connecting to server. If password is
not given it's asked from the tty.
-W, --pipe Use named pipes to connect to server.
-P, --port=# Port number to use for connection or 0 for default to, in
order of preference, my.cnf, $MYSQL_TCP_PORT,
/etc/services, built-in default (3306).
--progress-reports Get progress reports for long running commands (like
ALTER TABLE)
(Defaults to on; use --skip-progress-reports to disable.)
--prompt=name Set the mysql prompt to this value.
--protocol=name The protocol to use for connection (tcp, socket, pipe,
memory).
-q, --quick Don't cache result, print it row by row. This may slow
down the server if the output is suspended. Doesn't use
history file.
-r, --raw Write fields without conversion. Used with --batch.
--reconnect Reconnect if the connection is lost. Disable with
--disable-reconnect. This option is enabled by default.
(Defaults to on; use --skip-reconnect to disable.)
-s, --silent Be more silent. Print results with a tab as separator,
each row on new line.
--shared-memory-base-name=name
Base name of shared memory.
-S, --socket=name The socket file to use for connection.
--ssl Enable SSL for connection (automatically enabled with
other flags).
--ssl-ca=name CA file in PEM format (check OpenSSL docs, implies
--ssl).
--ssl-capath=name CA directory (check OpenSSL docs, implies --ssl).
--ssl-cert=name X509 cert in PEM format (implies --ssl).
--ssl-cipher=name SSL cipher to use (implies --ssl).
--ssl-key=name X509 key in PEM format (implies --ssl).
--ssl-crl=name Certificate revocation list (implies --ssl).
--ssl-crlpath=name Certificate revocation list path (implies --ssl).
--ssl-verify-server-cert
Verify server's "Common Name" in its cert against
hostname used when connecting. This option is disabled by
default.
-t, --table Output in table format.
--tee=name Append everything into outfile. See interactive help (\h)
also. Does not work in batch mode. Disable with
--disable-tee. This option is disabled by default.
-u, --user=name User for login if not current user.
-U, --safe-updates Only allow UPDATE and DELETE that uses keys.
-U, --i-am-a-dummy Synonym for option --safe-updates, -U.
-v, --verbose Write more. (-v -v -v gives the table output format).
-V, --version Output version information and exit.
-w, --wait Wait and retry if connection is down.
--connect-timeout=# Number of seconds before connection timeout.
--max-allowed-packet=#
The maximum packet length to send to or receive from
server.
--net-buffer-length=#
The buffer size for TCP/IP and socket communication.
--select-limit=# Automatic limit for SELECT when using --safe-updates.
--max-join-size=# Automatic limit for rows in a join when using
--safe-updates.
--secure-auth Refuse client connecting to server if it uses old
(pre-4.1.1) protocol.
--server-arg=name Send embedded server this as a parameter.
--show-warnings Show warnings after every statement.
--plugin-dir=name Directory for client-side plugins.
--default-auth=name Default authentication client-side plugin to use.
--binary-mode By default, ASCII '\0' is disallowed and '\r\n' is
translated to '\n'. This switch turns off both features,
and also turns off parsing of all clientcommands except
\C and DELIMITER, in non-interactive mode (for input
piped to mysql or loaded using the 'source' command).
This is necessary when processing output from mysqlbinlog
that may contain blobs.
Variables (--variable-name=value)
and boolean options {FALSE|TRUE} Value (after reading options)
--------------------------------- ----------------------------------------
abort-source-on-error FALSE
auto-rehash FALSE
auto-vertical-output FALSE
character-sets-dir (No default value)
column-type-info FALSE
comments FALSE
compress FALSE
debug-check FALSE
debug-info FALSE
database (No default value)
default-character-set auto
delimiter ;
vertical FALSE
force FALSE
named-commands FALSE
ignore-spaces FALSE
init-command (No default value)
local-infile FALSE
no-beep FALSE
host localhost
html FALSE
xml FALSE
line-numbers TRUE
unbuffered FALSE
column-names TRUE
sigint-ignore FALSE
port 3306
progress-reports TRUE
prompt \N [\d]>
quick FALSE
raw FALSE
reconnect TRUE
shared-memory-base-name (No default value)
socket C:/xampp/mysql/mysql.sock
ssl FALSE
ssl-ca (No default value)
ssl-capath (No default value)
ssl-cert (No default value)
ssl-cipher (No default value)
ssl-key (No default value)
ssl-crl (No default value)
ssl-crlpath (No default value)
ssl-verify-server-cert FALSE
table FALSE
user (No default value)
safe-updates FALSE
i-am-a-dummy FALSE
connect-timeout 0
max-allowed-packet 16777216
net-buffer-length 16384
select-limit 1000
max-join-size 1000000
secure-auth FALSE
show-warnings FALSE
plugin-dir (No default value)
default-auth (No default value)
binary-mode FALSE
Any image that has a link will have a border around the image to help indicate it is a link with older browsers. Adding border="0" to your IMG HTML tag will prevent that picture from having a border around the image.
However, adding border="0" to every image would not only be time consuming it will also increase the file size and download time. If you don't want any of your images to have a border, create a CSS rule or CSS file that has the below code in it.
img { border-style: none; }
Make sure that the actual .vim
file is in ~/.vim/plugin/
If you can't start Wamp anymore right after a Windows update, this is often caused because of Windows that has automatically re-turned on the World Wide Web Publishing Service.
To solve: Click on Start, type Services, click Services, find World Wide Web Publishing Service, double click it, set Startup type to Disabled and click Stop button, OK this dialog and try to restart Wamp.
UPDATE users SET username='&username', password='&password' where id='&id'
This query will ask you to enter the username,password and id dynamically
To expand on the answer from 'levi' and to show how to get the response from the upload so you can process the file upload:
selectFile(event) {
event.preventDefault();
file_input = document.createElement('input');
file_input.addEventListener("change", uploadFile, false);
file_input.type = 'file';
file_input.click();
},
uploadFile() {
let dataArray = new FormData();
dataArray.append('file', file_input.files[0]);
// Obviously, you can substitute with JQuery or whatever
axios.post('/your_super_special_url', dataArray).then(function() {
//
});
}
Im new to RoR this is what I found out. you can directly render a json format
def YOUR_METHOD_HERE
users = User.all
render json: {allUsers: users} # ! rendering all users
END
Try assigning a value to $aug1
before use it in if[]
statements; the error message will disappear afterwards.
Some databases are designed to communicate over the web using ports assigned by the Internet Assigned Number Authority (IANA) and when run on individual PC use the ports with localhost. Some common databases with their default ports (the defualts can usually be overridden):
Port Database
1433 Microsoft SQL Server https://support.microsoft.com/en-us/kb/287932
3306 MySQL https://dev.mysql.com/doc/refman/4.1/en/connecting.html
5432 PostgreSQL
1527 Apache Derby (database)
Some web servers and databases are paired together such as Apache/MySQL (as in LAMP or XXAMP) or MS Internet Information Server (IIS)/MS SQL Server (IIS/SQL Server) in which case you have to be concerned with both the port of the database and the web server -- a common example of this is WordPress which uses Apache/MySQL.
let say you've imported math and re:
>>import math,re
now to see the same use
>>print(dir())
If you run it before the import and after the import, one can see the difference.
Assuming we imported pandas as pd
and df
is our dataframe
pd.to_datetime(df['date'], unit='s')
works for me.
The type int
is a primitive and it cannot be null
, if you want to return null
, mark the signature as
public Integer pollDecrementHigherKey(int x) {
x = 10;
if (condition) {
return x; // This is auto-boxing, x will be automatically converted to Integer
} else if (condition2) {
return null; // Integer inherits from Object, so it's valid to return null
} else {
return new Integer(x); // Create an Integer from the int and then return
}
return 5; // Also will be autoboxed and converted into Integer
}
If you don't have access to the v$ views (as suggested by Quassnoi) there are two alternatives
select utl_inaddr.get_host_name from dual
and
select sys_context('USERENV','SERVER_HOST') from dual
Personally I'd tend towards the last as it doesn't require any grants/privileges which makes it easier from stored procedures.
The easiest way is to just learn how to do DOM traversing and manipulation with the plain DOM api (you would probably call this: normal JavaScript).
This can however be a pain for some things. (which is why libraries were invented in the first place).
Googling for "javascript DOM traversing/manipulation" should present you with plenty of helpful (and some less helpful) resources.
The articles on this website are pretty good: http://www.htmlgoodies.com/primers/jsp/
And as Nosredna points out in the comments: be sure to test in all browsers, because now jQuery won't be handling the inconsistencies for you.
Create index.html
or index.php
file in root directory (in your case - /var/www/html
, as @jabaldonedo mentioned)
Try this technique; It returns the desired result
CultureInfo.CurrentCulture.TextInfo.ToTitleCase(str.ToLower());
And don't forget to use System.Globalization
.
add this permission in your manifest and than use the above code to change WiFi state:
<!--permission ge enable and disable WIFI in android-->
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
have you tried doing it without the JSON object and just passed two basicnamevaluepairs? also, it might have something to do with your serversettings
Update: this is a piece of code I use:
InputStream is = null;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("lastupdate", lastupdate));
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(connection);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.d("HTTP", "HTTP: OK");
} catch (Exception e) {
Log.e("HTTP", "Error in http connection " + e.toString());
}
Use COALESCE()
instead:
SELECT COALESCE(Field,'Empty') from Table;
It functions much like ISNULL
, although provides more functionality. Coalesce will return the first non null value in the list. Thus:
SELECT COALESCE(null, null, 5);
returns 5, while
SELECT COALESCE(null, 2, 5);
returns 2
Coalesce will take a large number of arguments. There is no documented maximum. I tested it will 100 arguments and it succeeded. This should be plenty for the vast majority of situations.
I had exactly the same problem, my solution was to use module definition file (.def) instead of __declspec(dllexport)
to define exports(http://msdn.microsoft.com/en-us/library/d91k01sh.aspx). I have no idea why this works, but it does
It looks like your 'trainData' is a list of strings:
['-214' '-153' '-58' ..., '36' '191' '-37']
Change your 'trainData' to a numeric type.
import numpy as np
np.array(['1','2','3']).astype(np.float)
Complementing the @slonik's answer.
You can test socat to create Virtual Serial Port doing the following procedure (tested on Ubuntu 12.04):
Open a terminal (let's call it Terminal 0) and execute it:
socat -d -d pty,raw,echo=0 pty,raw,echo=0
The code above returns:
2013/11/01 13:47:27 socat[2506] N PTY is /dev/pts/2
2013/11/01 13:47:27 socat[2506] N PTY is /dev/pts/3
2013/11/01 13:47:27 socat[2506] N starting data transfer loop with FDs [3,3] and [5,5]
Open another terminal and write (Terminal 1):
cat < /dev/pts/2
this command's port name can be changed according to the pc. it's depends on the previous output.
2013/11/01 13:47:27 socat[2506] N PTY is /dev/pts/**2**
2013/11/01 13:47:27 socat[2506] N PTY is /dev/pts/**3**
2013/11/01 13:47:27 socat[2506] N starting data transfer loop with FDs
you should use the number available on highlighted area.
Open another terminal and write (Terminal 2):
echo "Test" > /dev/pts/3
Now back to Terminal 1 and you'll see the string "Test".
Replace [ with nothing, then ] with nothing.
The way of changing the name for iOS and Android is clearly mentioned in the documentation as follows:
But, the case of iOS after you change the Display Name from Xcode, you are not able to run the application in the Flutter way, like flutter run
.
Because the Flutter run expects the app name as Runner. Even if you change the name in Xcode, it doesn't work.
So, I fixed this as follows:
Move to the location on your Flutter project, ios/Runner.xcodeproj/project.pbxproj, and find and replace all instances of your new name with Runner.
Then everything should work in the flutter run
way.
But don't forget to change the name display name on your next release time. Otherwise, the App Store rejects your name.
For the question
How can i run a jar file in command prompt but with arguments
.
To pass arguments to the jar file at the time of execution
java -jar myjar.jar arg1 arg2
In the main() method of "Main-Class" [mentioned in the manifest.mft file]of your JAR file. you can retrieve them like this:
String arg1 = args[0];
String arg2 = args[1];
Why not just use key name on dictionary, C# has this:
Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("UserID", "test");
string userIDFromDictionaryByKey = dict["UserID"];
If you look at the tip suggestion:
How about this? (jsFiddle link)
CSS
ul {
background: #CCC;
height: 1000%;
width: 100%;
list-style-position: outside;
margin: 0; padding: 0;
position: absolute;
}
li {
background-color: #EBEBEB;
border-bottom: 1px solid #CCCCCC;
border-right: 1px solid #CCCCCC;
display: table;
height: 180px;
overflow: hidden;
width: 200px;
}
.divone{
display: table-cell;
margin: 0 auto;
text-align: center;
vertical-align: middle;
width: 100%;
}
img {
width: 100%;
height: 410px;
}
.wrapper {
position: absolute;
}
In cases where the name attribute is different it is easiest to control the radio group via JQuery. When an option is selected use JQuery to un-select the other options.
Since PyYAML's yaml.load()
function parses YAML documents to native Python data structures, you can just access items by key or index. Using the example from the question you linked:
import yaml
with open('tree.yaml', 'r') as f:
doc = yaml.load(f)
To access branch1 text
you would use:
txt = doc["treeroot"]["branch1"]
print txt
"branch1 text"
because, in your YAML document, the value of the branch1
key is under the treeroot
key.
You can use ComboBox, then point your mouse to the upper arrow facing right, it will unfold a box called ComboBox Tasks and in there you can go ahead and edit your items or fill in the items / strings one per line. This should be the easiest.
I have tried several solutions mentioned over web, unfortunately without any success. In my project, I have two interfaces(xml/json) for each service. Adding mex endpoints or binding configurations did not helped at all. But, I have noticed, I get this error only when running project with *.svc.cs or *.config file focused. When I run project with IService.cs file focused (where interfaces are defined), service is added without any errors. This is really strange and in my opinion conclusion is bug in Visual Studio 2013. I reproduced same behaviour on several machines(even on Windows Server machine). Hope this helps someone.
You map your dispatcher on *.do:
<servlet-mapping>
<servlet-name>Dispatcher</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
but your controller is mapped on an url without .do:
@RequestMapping("/editPresPage")
Try changing this to:
@RequestMapping("/editPresPage.do")
there are two ways of doing it either you can use XML or Java for it. If it's static and requires no changes then you can initialize in XML.
android:drawableLeft="@drawable/cloud_up"
android:drawablePadding="5sp"
Now if you need to change the icons dynamically then you can do it by calling the icons based on the events
textViewContext.setText("File Uploaded");
textViewContext.setCompoundDrawablesWithIntrinsicBounds(R.drawable.uploaded, 0, 0, 0);
Try below code:
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));// set transparent in window background
View _v = inflater.inflate(R.layout.some_you_layout, container, false);
//load animation
//Animation transition_in_view = AnimationUtils.loadAnimation(getContext(), android.R.anim.fade_in);// system animation appearance
Animation transition_in_view = AnimationUtils.loadAnimation(getContext(), R.anim.customer_anim);//customer animation appearance
_v.setAnimation( transition_in_view );
_v.startAnimation( transition_in_view );
//really beautiful
return _v;
}
Create the custom Anim.: res/anim/customer_anim.xml:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate
android:duration="500"
android:fromYDelta="100%"
android:toYDelta="-7%"/>
<translate
android:duration="300"
android:startOffset="500"
android:toYDelta="7%" />
<translate
android:duration="200"
android:startOffset="800"
android:toYDelta="0%" />
</set>
Be careful, the solution proposed with $a = array_combine($a, $a);
will not work for numeric values.
I for example wanted to have a memory array(128,256,512,1024,2048,4096,8192,16384)
to be the keys as well as the values however PHP manual states:
If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.
So I solved it like this:
foreach($array as $key => $val) {
$new_array[$val]=$val;
}
Django also has the 'latest(field_name = None)' function that finds the latest (max. value) entry. It not only works with date fields but also with strings and integers.
You can give the field name when calling that function:
max_rated_entry = YourModel.objects.latest('rating')
return max_rated_entry.details
Or you can already give that field name in your models meta data:
from django.db import models
class YourModel(models.Model):
#your class definition
class Meta:
get_latest_by = 'rating'
Now you can call 'latest()' without any parameters:
max_rated_entry = YourModel.objects.latest()
return max_rated_entry.details
You can use tcpkill
(part of the dsniff
package) to kill the connection that's on the port you need:
sudo tcpkill -9 port PORT_NUMBER
While the accepted answer solved the OP's original problem, most people finding this question through a Google search are likely having an entirely different problem which just happens to throw the same no suitable HttpMessageConverter found exception.
What happens under the covers is that MappingJackson2HttpMessageConverter
swallows any exceptions that occur in its canRead()
method, which is supposed to auto-detect whether the payload is suitable for json decoding. The exception is replaced by a simple boolean return that basically communicates sorry, I don't know how to decode this message to the higher level APIs (RestClient
). Only after all other converters' canRead() methods return false, the no suitable HttpMessageConverter found exception is thrown by the higher-level API, totally obscuring the true problem.
For people who have not found the root cause (like you and me, but not the OP), the way to troubleshoot this problem is to place a debugger breakpoint on onMappingJackson2HttpMessageConverter.canRead()
, then enable a general breakpoint on any exception, and hit Continue. The next exception is the true root cause.
My specific error happened to be that one of the beans referenced an interface that was missing the proper deserialization annotations.
UPDATE FROM THE FUTURE
This has proven to be such a recurring issue across so many of my projects, that I've developed a more proactive solution. Whenever I have a need to process JSON exclusively (no XML or other formats), I now replace my RestTemplate
bean with an instance of the following:
public class JsonRestTemplate extends RestTemplate {
public JsonRestTemplate(
ClientHttpRequestFactory clientHttpRequestFactory) {
super(clientHttpRequestFactory);
// Force a sensible JSON mapper.
// Customize as needed for your project's definition of "sensible":
ObjectMapper objectMapper = new ObjectMapper()
.registerModule(new Jdk8Module())
.registerModule(new JavaTimeModule())
.configure(
SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
MappingJackson2HttpMessageConverter jsonMessageConverter = new MappingJackson2HttpMessageConverter() {
public boolean canRead(java.lang.Class<?> clazz,
org.springframework.http.MediaType mediaType) {
return true;
}
public boolean canRead(java.lang.reflect.Type type,
java.lang.Class<?> contextClass,
org.springframework.http.MediaType mediaType) {
return true;
}
protected boolean canRead(
org.springframework.http.MediaType mediaType) {
return true;
}
};
jsonMessageConverter.setObjectMapper(objectMapper);
messageConverters.add(jsonMessageConverter);
super.setMessageConverters(messageConverters);
}
}
This customization makes the RestClient
incapable of understanding anything other than JSON. The upside is that any error messages that may occur will be much more explicit about what's wrong.
You can start Android Device Monitor from the Android Studio (green robot icon on the toolbar, to the left of the help icon). From the ADM, select the device/emulator, then select the File Explorer tab.
You can send a prop from the parent and use it in child component so you will base child's state changes on the sent prop changes and you can handle this by using getDerivedStateFromProps in the child component.
It is the answer of @Robert Longson, now with code (there was originally no code, it was added later):
<?xml version="1.0" encoding="UTF-8"?>_x000D_
<svg version="1.1" xmlns="http://www.w3.org/2000/svg">_x000D_
<rect width="100%" height="100%" fill="red"/>_x000D_
</svg>
_x000D_
This answer uses:
This is an old post but regardless, you can also get boldface and italic characters by leveraging utf-32. There are even greek and math symbols that can be used as well as the roman alphabet.
Every control that uses Collections to store data have SelectedValue, SelectedItem property. Examples of these controls are ListBox, Dropdown, RadioButtonList, CheckBoxList.
To be more specific if you literally want to retrieve Text of Selected Item then you can write:
ListBox1.SelectedItem.Text;
Your ListBox1 can also return Text using SelectedValue property if value has set to that before. But above is more effective way to get text.
Now, the value is something that is not visible to user but it is used mostly to store in database. We don't insert Text of ListBox1, however we can insert it also, but we used to insert value of selected item. To get value we can use
ListBox1.SelectedValue
public static int[] removeDuplicates(int[] input){
int j = 0;
int i = 1;
//return if the array length is less than 2
if(input.length < 2){
return input;
}
while(i < input.length){
if(input[i] == input[j]){
i++;
}else{
j = j+1;
input[j] = input[i];
i = i+1;
}
}
int[] output = new int[j+1];
for(int k=0; k<output.length; k++){
output[k] = input[k];
}
return output;
}
public static void main(String a[]){
int[] input1 = {2,3,6,6,8,9,10,10,10,12,12};
int[] output = removeDuplicates(input1);
for(int i:output){
System.out.println(i+" ");
}
}
For linux users: possible solution.
Build error due to "Failed to delete < any-file-or-folder >" will occur if there is by chance of only delete access provided to root user rather to normal-user.
Fix : type ll command to list file that cannot be deleted, if the file is given root access, change to normal user by :
sudo chown -R user-name:user-name filename
Later try for maven clean and build.
Calling
for /?
in the command-line gives help about this syntax (which can be used outside FOR, too, this is just the place where help can be found).
In addition, substitution of FOR variable references has been enhanced. You can now use the following optional syntax:
%~I - expands %I removing any surrounding quotes (") %~fI - expands %I to a fully qualified path name %~dI - expands %I to a drive letter only %~pI - expands %I to a path only %~nI - expands %I to a file name only %~xI - expands %I to a file extension only %~sI - expanded path contains short names only %~aI - expands %I to file attributes of file %~tI - expands %I to date/time of file %~zI - expands %I to size of file %~$PATH:I - searches the directories listed in the PATH environment variable and expands %I to the fully qualified name of the first one found. If the environment variable name is not defined or the file is not found by the search, then this modifier expands to the empty string
The modifiers can be combined to get compound results:
%~dpI - expands %I to a drive letter and path only %~nxI - expands %I to a file name and extension only %~fsI - expands %I to a full path name with short names only %~dp$PATH:I - searches the directories listed in the PATH environment variable for %I and expands to the drive letter and path of the first one found. %~ftzaI - expands %I to a DIR like output line
In the above examples %I and PATH can be replaced by other valid values. The %~ syntax is terminated by a valid FOR variable name. Picking upper case variable names like %I makes it more readable and avoids confusion with the modifiers, which are not case sensitive.
There are different letters you can use like f
for "full path name", d
for drive letter, p
for path, and they can be combined. %~
is the beginning for each of those sequences and a number I
denotes it works on the parameter %I
(where %0
is the complete name of the batch file, just like you assumed).
example code taking all 4 cores on my ubuntu 14.04, python 2.7 64 bit.
import time
import threading
def t():
with open('/dev/urandom') as f:
for x in xrange(100):
f.read(4 * 65535)
if __name__ == '__main__':
start_time = time.time()
t()
t()
t()
t()
print "Sequential run time: %.2f seconds" % (time.time() - start_time)
start_time = time.time()
t1 = threading.Thread(target=t)
t2 = threading.Thread(target=t)
t3 = threading.Thread(target=t)
t4 = threading.Thread(target=t)
t1.start()
t2.start()
t3.start()
t4.start()
t1.join()
t2.join()
t3.join()
t4.join()
print "Parallel run time: %.2f seconds" % (time.time() - start_time)
result:
$ python 1.py
Sequential run time: 3.69 seconds
Parallel run time: 4.82 seconds
You can use the dotenv package no matter what setup you use. It allows you to create a .env in your project root and specify your keys like so
REACT_APP_SERVER_PORT=8000
In your applications entry file your just call dotenv(); before accessing the keys like so
process.env.REACT_APP_SERVER_PORT
This is an old tread with different solution proposed, but none of them worked for me. I'm adding this answer in the hope it will help somebody who struggled as me for some time.
I've checked all the existing answers and all the existing solution, but for me the issue was incorrect user permission on var/run/mysql
folder.
I've checked the user permission on that folder and it was set to root
. Once i changed to mysql:mysql
the problem has gone.
So enter into /var/run/mysqld
and change the user permission to:
chown -R mysql:mysql .
From the GCC 4.2.1 manual, section -fwhole-program
:
Assume that the current compilation unit represents whole program being compiled. All public functions and variables with the exception of
main
and those merged by attributeexternally_visible
become static functions and in a affect gets more aggressively optimized by interprocedural optimizers. While this option is equivalent to proper use ofstatic
keyword for programs consisting of single file, in combination with option--combine
this flag can be used to compile most of smaller scale C programs since the functions and variables become local for the whole combined compilation unit, not for the single source file itself.
function DateDiff(b, e)
{
let
endYear = e.getFullYear(),
endMonth = e.getMonth(),
years = endYear - b.getFullYear(),
months = endMonth - b.getMonth(),
days = e.getDate() - b.getDate();
if (months < 0)
{
years--;
months += 12;
}
if (days < 0)
{
months--;
days += new Date(endYear, endMonth, 0).getDate();
}
return [years, months, days];
}
[years, months, days] = DateDiff(
new Date("October 21, 1980"),
new Date("July 11, 2017")); // 36 8 20
CenterSpace's NMath library provides a function:
double[] values = new double[arraySize];
double median = NMathFunctions.Median(values);
Optionally you can opt to use NaNMedian (if your array may contain null values) but you will need to convert the array to a vector:
double median = NMathFunctions.NaNMedian(new DoubleVector(values));
CenterSpace's NMath Library isn't free, but many universities have licenses
You can try doing
<p>
<a href="MY WEBSITE LINK" target="_blank">
<img src="IMAGE LINK" style='width:100%;' border="0" alt="Null">
</a>
</p>
This should scale your image if in a fluid layout.
For responsive (meaning your layout reacts to the size of the window) you can add a class to the image and use @media
queries in CSS to change the width of the image.
Note that changing the height of the image will mess with the ratio.
Below is a simple function implementation which splits a DataFrame to chunks and a few code examples:
import pandas as pd
def split_dataframe_to_chunks(df, n):
df_len = len(df)
count = 0
dfs = []
while True:
if count > df_len-1:
break
start = count
count += n
#print("%s : %s" % (start, count))
dfs.append(df.iloc[start : count])
return dfs
# Create a DataFrame with 10 rows
df = pd.DataFrame([i for i in range(10)])
# Split the DataFrame to chunks of maximum size 2
split_df_to_chunks_of_2 = split_dataframe_to_chunks(df, 2)
print([len(i) for i in split_df_to_chunks_of_2])
# prints: [2, 2, 2, 2, 2]
# Split the DataFrame to chunks of maximum size 3
split_df_to_chunks_of_3 = split_dataframe_to_chunks(df, 3)
print([len(i) for i in split_df_to_chunks_of_3])
# prints [3, 3, 3, 1]
for my script of python, I use...
To START python script :
start-stop-daemon --start --background --pidfile $PIDFILE --make-pidfile --exec $DAEMON
To STOP python script :
PID=$(cat $PIDFILE)
kill -9 $PID
rm -f $PIDFILE
P.S.: sorry for poor English, I'm from CHILE :D
Incase their is local uncommitted changes and avoid merge conflict while pulling.
git stash save
git pull
git stash pop
I had the same problem, in my case because i forgot this in my NavBar style: overflow: hidden;
Two steps works fine:
create table bu_x as (select a,b,c,d from x ) WITH no data;
insert into bu_x (a,b,c,d) select select a,b,c,d from x ;
According to the pytest docs, pytest --capture=sys
should work. If you want to capture standard out inside a test, refer to the capsys fixture.
If you are trying to read a file, that will take up memory in PHP. For instance, if you are trying to open up and read an MP3 file ( like, say, $data = file("http://mydomain.com/path/sample.mp3" ) it is going to pull it all into memory.
As Nelson suggests, you can work to increase your maximum memory limit if you actually need to be using this much memory.
Assuming you're the administrator of the machine, Ubuntu has granted you the right to sudo to run any command as any user.
Also assuming you did not restrict the rights in the pg_hba.conf
file (in the /etc/postgresql/9.1/main
directory), it should contain this line as the first rule:
# Database administrative login by Unix domain socket
local all postgres peer
(About the file location: 9.1
is the major postgres version and main
the name of your "cluster". It will differ if using a newer version of postgres or non-default names. Use the pg_lsclusters
command to obtain this information for your version/system).
Anyway, if the pg_hba.conf
file does not have that line, edit the file, add it, and reload the service with sudo service postgresql reload
.
Then you should be able to log in with psql
as the postgres superuser with this shell command:
sudo -u postgres psql
Once inside psql, issue the SQL command:
ALTER USER postgres PASSWORD 'newpassword';
In this command, postgres
is the name of a superuser. If the user whose password is forgotten was ritesh
, the command would be:
ALTER USER ritesh PASSWORD 'newpassword';
References: PostgreSQL 9.1.13 Documentation, Chapter 19. Client Authentication
Keep in mind that you need to type postgres with a single S at the end
If leaving the password in clear text in the history of commands or the server log is a problem, psql provides an interactive meta-command to avoid that, as an alternative to ALTER USER ... PASSWORD
:
\password username
It asks for the password with a double blind input, then hashes it according to the password_encryption
setting and issue the ALTER USER
command to the server with the hashed version of the password, instead of the clear text version.
You can get everything through ExternalContext
. In JSF 1.x, you can get the raw HttpServletResponse
object by ExternalContext#getResponse()
. In JSF 2.x, you can use the bunch of new delegate methods like ExternalContext#getResponseOutputStream()
without the need to grab the HttpServletResponse
from under the JSF hoods.
On the response, you should set the Content-Type
header so that the client knows which application to associate with the provided file. And, you should set the Content-Length
header so that the client can calculate the download progress, otherwise it will be unknown. And, you should set the Content-Disposition
header to attachment
if you want a Save As dialog, otherwise the client will attempt to display it inline. Finally just write the file content to the response output stream.
Most important part is to call FacesContext#responseComplete()
to inform JSF that it should not perform navigation and rendering after you've written the file to the response, otherwise the end of the response will be polluted with the HTML content of the page, or in older JSF versions, you will get an IllegalStateException
with a message like getoutputstream() has already been called for this response
when the JSF implementation calls getWriter()
to render HTML.
You only need to make sure that the action method is not called by an ajax request, but that it is called by a normal request as you fire with <h:commandLink>
and <h:commandButton>
. Ajax requests and remote commands are handled by JavaScript which in turn has, due to security reasons, no facilities to force a Save As dialogue with the content of the ajax response.
In case you're using e.g. PrimeFaces <p:commandXxx>
, then you need to make sure that you explicitly turn off ajax via ajax="false"
attribute. In case you're using ICEfaces, then you need to nest a <f:ajax disabled="true" />
in the command component.
public void download() throws IOException {
FacesContext fc = FacesContext.getCurrentInstance();
ExternalContext ec = fc.getExternalContext();
ec.responseReset(); // Some JSF component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide.
ec.setResponseContentType(contentType); // Check http://www.iana.org/assignments/media-types for all types. Use if necessary ExternalContext#getMimeType() for auto-detection based on filename.
ec.setResponseContentLength(contentLength); // Set it with the file size. This header is optional. It will work if it's omitted, but the download progress will be unknown.
ec.setResponseHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); // The Save As popup magic is done here. You can give it any file name you want, this only won't work in MSIE, it will use current request URL as file name instead.
OutputStream output = ec.getResponseOutputStream();
// Now you can write the InputStream of the file to the above OutputStream the usual way.
// ...
fc.responseComplete(); // Important! Otherwise JSF will attempt to render the response which obviously will fail since it's already written with a file and closed.
}
public void download() throws IOException {
FacesContext fc = FacesContext.getCurrentInstance();
HttpServletResponse response = (HttpServletResponse) fc.getExternalContext().getResponse();
response.reset(); // Some JSF component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide.
response.setContentType(contentType); // Check http://www.iana.org/assignments/media-types for all types. Use if necessary ServletContext#getMimeType() for auto-detection based on filename.
response.setContentLength(contentLength); // Set it with the file size. This header is optional. It will work if it's omitted, but the download progress will be unknown.
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); // The Save As popup magic is done here. You can give it any file name you want, this only won't work in MSIE, it will use current request URL as file name instead.
OutputStream output = response.getOutputStream();
// Now you can write the InputStream of the file to the above OutputStream the usual way.
// ...
fc.responseComplete(); // Important! Otherwise JSF will attempt to render the response which obviously will fail since it's already written with a file and closed.
}
In case you need to stream a static file from the local disk file system, substitute the code as below:
File file = new File("/path/to/file.ext");
String fileName = file.getName();
String contentType = ec.getMimeType(fileName); // JSF 1.x: ((ServletContext) ec.getContext()).getMimeType(fileName);
int contentLength = (int) file.length();
// ...
Files.copy(file.toPath(), output);
In case you need to stream a dynamically generated file, such as PDF or XLS, then simply provide output
there where the API being used expects an OutputStream
.
E.g. iText PDF:
String fileName = "dynamic.pdf";
String contentType = "application/pdf";
// ...
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, output);
document.open();
// Build PDF content here.
document.close();
E.g. Apache POI HSSF:
String fileName = "dynamic.xls";
String contentType = "application/vnd.ms-excel";
// ...
HSSFWorkbook workbook = new HSSFWorkbook();
// Build XLS content here.
workbook.write(output);
workbook.close();
Note that you cannot set the content length here. So you need to remove the line to set response content length. This is technically no problem, the only disadvantage is that the enduser will be presented an unknown download progress. In case this is important, then you really need to write to a local (temporary) file first and then provide it as shown in previous chapter.
If you're using JSF utility library OmniFaces, then you can use one of the three convenient Faces#sendFile()
methods taking either a File
, or an InputStream
, or a byte[]
, and specifying whether the file should be downloaded as an attachment (true
) or inline (false
).
public void download() throws IOException {
Faces.sendFile(file, true);
}
Yes, this code is complete as-is. You don't need to invoke responseComplete()
and so on yourself. This method also properly deals with IE-specific headers and UTF-8 filenames. You can find source code here.
Remove files from -web/.setting&-admin/.setting
var filePath = context.Server.MapPath(Convert.ToString(ConfigurationManager.AppSettings["ErrorLogFile"]));
var file = new FileInfo(filePath);
file.Directory.Create();
If the directory already exists, this method does nothing.
var sw = new StreamWriter(filePath, true);
sw.WriteLine(Enter your message here);
sw.Close();
This seems an improvement:
> cols<-!(colnames(dt) %in% c("V1","V2","V3","V5"))
> new_dt<-subset(dt,,cols)
> cor(new_dt)
V4 V6 V7 V8 V9 V10
V4 1.0000000 0.14141578 -0.44466832 0.23697216 -0.1020074 0.48171747
V6 0.1414158 1.00000000 -0.21356218 -0.08510977 -0.1884202 -0.22242274
V7 -0.4446683 -0.21356218 1.00000000 -0.02050846 0.3209454 -0.15021528
V8 0.2369722 -0.08510977 -0.02050846 1.00000000 0.4627034 -0.07020571
V9 -0.1020074 -0.18842023 0.32094540 0.46270335 1.0000000 -0.19224973
V10 0.4817175 -0.22242274 -0.15021528 -0.07020571 -0.1922497 1.00000000
This one is not quite as easy to grasp but might have use for situations there there were a need to specify columns by a numeric vector:
subset(dt, , !grepl(paste0("V", c(1:3,5),collapse="|"),colnames(dt) ))
Unless you write your own Homescreen launcher or use an existing one from Goolge Play, there's "no way" to resize icons.
Well, "no way" does not mean its impossible:
You might try using @media query such as below.
Add a logo class first, then use @media to specify your logo height and width per device size. In the example below, I am targeting devices which have a max width of 320px (iPhone) You can play around with this until you find the best fit. Easy way to test: Use chrome or Firefox with inspect element. Shrink your browser as far as possible. Observe the logo size change based on the @media max width you specify. Test on iPhone, android devices, iPad etc to get the desired results.
.logo {
height: 42px;
width: 140px;
}
@media (max-width:320px) {
.logo {
height: 33px;
width: 110px;
}
}
Install tesseract from https://github.com/UB-Mannheim/tesseract/wiki and add the path of tesseract.exe to the Path environment variable.
int
and long
were "unified" a few versions back. Before that it was possible to overflow an int through math ops.
3.x has further advanced this by eliminating long altogether and only having int.
sys.maxint
contains the maximum value a Python int can hold.
sys.getsizeof()
.sys.maxsize
contains the maximum size in bytes a Python int can be.
sys.maxsize
.using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.DataVisualization.Charting;
using System.Web.UI.WebControls;
C#
string constring = ConfigurationManager.ConnectionStrings["ABCD"].ConnectionString;
using (SqlConnection con = new SqlConnection(constring))
BELOW WEB.CONFIG FILE CODE
<connectionStrings>
<add name="ABCD" connectionString="Data Source=DESKTOP-SU3NKUU\MSSQLSERVER2016;Initial Catalog=TESTKISWRMIP;Integrated Security=True" providerName="System.Data.SqlClient"/>
</connectionStrings>
In the above Code ABCD is the Connection Name
str="abcdef"
str.index('c') #=> 2 #String matching approach
str=~/c/ #=> 2 #Regexp approach
$~ #=> #<MatchData "c">
Hope it helps. :)
Here's a query to update a table based on a comparison of another table. If record is not found in tableB, it will update the "active" value to "n". If it's found, will set the value to NULL
UPDATE tableA
LEFT JOIN tableB ON tableA.id = tableB.id
SET active = IF(tableB.id IS NULL, 'n', NULL)";
Hope this helps someone else.
If you inherit publicly from another class, everybody knows you are inheriting and you can be used polymorphically by anyone through a base class pointer.
If you inherit protectedly only your children classes will be able to use you polymorphically.
If you inherit privately only yourself will be able to execute parent class methods.
Which basically symbolizes the knowledge the rest of the classes have about your relationship with your parent class
Use a scalar-valued UDF, not a table-value one, then you can use it in a SELECT as you want.
Recursion is an alternative to loops, it's quite seldom that they bring more clearness or elegance to your code. A good example was given by Progman's answer, if he wouldn't use recursion he would be forced to keep track in which directory he is currently (this is called state) recursions allows him to do the bookkeeping using the stack (the area where variables and return adress of a method are stored)
The standard examples factorial and Fibonacci are not useful for understanding the concept because they're easy to replace by a loop.
index.php
$url = 'http://[host]/test.php';
$json = json_encode(['name' => 'Jhonn', 'phone' => '128000000000']);
$options = ['http' => [
'method' => 'POST',
'header' => 'Content-type:application/json',
'content' => $json
]];
$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);
test.php
$raw = file_get_contents('php://input');
$data = json_decode($raw, true);
echo $data['name']; // Jhonn
"We usually put ' (space)' after the first sentence before a new line, but it doesn't work in Jupyter."
That inspired me to try using two spaces instead of just one - and it worked!!
(Of course, that functionality could possibly have been introduced between when the question was asked in January 2017, and when my answer was posted in March 2018.)
From 5.2.2/2 (character display semantics) :
\b
(backspace) Moves the active position to the previous position on the current line. If the active position is at the initial position of a line, the behavior of the display device is unspecified.
\n
(new line) Moves the active position to the initial position of the next line.
\r
(carriage return) Moves the active position to the initial position of the current line.
Here, your code produces :
<new_line>ab
\b
: back one charactersi
: overrides the b
with s
(producing asi
on the second line)\r
: back at the beginning of the current lineha
: overrides the first two characters (producing hai
on the second line)In the end, the output is :
\nhai
Almost 9 years late to this but didn't see this variation mentioned accomplishing the same thing (it's kind of a combination of a few of these, similar to to top answer (https://stackoverflow.com/a/1459264/4642530).
Search all detached heads on branch
git reflog show origin/BRANCH_NAME --date=relative
Then find the SHA1 hash
Reset to old SHA1
git reset --hard SHA1
Then push it back up.
git push origin BRANCH_NAME
Done.
This will revert you back to the old commit entirely.
(Including the date of the prior overwritten detached commit head)
Your constructor is expecting one parameter (data). You're not passing it in the call. I guess you wanted to initialise a field in the object. That would look like this:
class DHT:
def __init__(self):
self.data = {}
self.data['one'] = '1'
self.data['two'] = '2'
self.data['three'] = '3'
def showData(self):
print(self.data)
if __name__ == '__main__':
DHT().showData()
Or even just:
class DHT:
def __init__(self):
self.data = {'one': '1', 'two': '2', 'three': '3'}
def showData(self):
print(self.data)
First add the # -*- coding: utf-8 -*-
line to the beginning of the file and then use u'foo'
for all your non-ASCII unicode data:
def NewFunction():
return u'£'
or use the magic available since Python 2.6 to make it automatic:
from __future__ import unicode_literals
Actually in Eclipse Indigo thru Oxygen, you have to go to the Types template Window -> Preferences -> Java -> Code Style -> Code templates -> (in right-hand pane) Comments -> double-click Types
and make sure it has the following, which it should have by default:
/**
* @author ${user}
*
* ${tags}
*/
and as far as I can tell, there is nothing in Eclipse to add the javadoc automatically to existing files in one batch. You could easily do it from the command line with sed
& awk
but that's another question.
If you are prepared to open each file individually, then selected the class / interface declaration line, e.g. public class AdamsClass { and then hit the key combo Shift + Alt + J and that will insert a new javadoc comment above, along with the author tag for your user. To experiment with other settings, go to Windows->Preferences->Java->Editor->Templates
.
It's been a while since I C++'d but these answers are off a bit.
As far as the size goes, 'int' isn't anything. It's a notional value of a standard integer; assumed to be fast for purposes of things like iteration. It doesn't have a preset size.
So, the answers are correct with respect to the differences between int and uint, but are incorrect when they talk about "how large they are" or what their range is. That size is undefined, or more accurately, it will change with the compiler and platform.
It's never polite to discuss the size of your bits in public.
When you compile a program, int does have a size, as you've taken the abstract C/C++ and turned it into concrete machine code.
So, TODAY, practically speaking with most common compilers, they are correct. But do not assume this.
Specifically: if you're writing a 32 bit program, int will be one thing, 64 bit, it can be different, and 16 bit is different. I've gone through all three and briefly looked at 6502 shudder
A brief google search shows this: https://www.tutorialspoint.com/cprogramming/c_data_types.htm This is also good info: https://docs.oracle.com/cd/E19620-01/805-3024/lp64-1/index.html
use int if you really don't care how large your bits are; it can change.
Use size_t and ssize_t if you want to know how large something is.
If you're reading or writing binary data, don't use int. Use a (usually platform/source dependent) specific keyword. WinSDK has plenty of good, maintainable examples of this. Other platforms do too.
I've spent a LOT of time going through code from people that "SMH" at the idea that this is all just academic/pedantic. These ate the people that write unmaintainable code. Sure, it's easy to use type 'int' and use it without all the extra darn typing. It's a lot of work to figure out what they really meant, and a bit mind-numbing.
It's crappy coding when you mix int.
use int and uint when you just want a fast integer and don't care about the range (other than signed/unsigned).
Try www.eclipse.org/downloads/packages/eclipse-android-developers-includes-incubating-components/neonrc3
There are at least two ways to solve this.
Solution 1:
If you are okay with using an absolutely positioned element, you can use the top
and bottom
properties instead of height
. By setting both top
and bottom
to 0
you force the element into taking up full height.
#menu
{
position: absolute;
border-right: 1px solid black;
top: 0;
bottom: 0;
}?
Solution 2:
Another way would be to force the HTML and BODY elements into a 100% height, to give room for a menu with 100% height:
body, html { height: 100%; }
#menu
{
border-right: 1px solid black;
height: 100%;
}?
How to show uncommitted changes in Git
The command you are looking for is git diff
.
git diff
- Show changes between commits, commit and working tree, etc
Here are some of the options it expose which you can use
git diff
(no parameters)
Print out differences between your working directory and the index.
git diff --cached
:
Print out differences between the index and HEAD (current commit).
git diff HEAD
:
Print out differences between your working directory and the HEAD.
git diff --name-only
Show only names of changed files.
git diff --name-status
Show only names and status of changed files.
git diff --color-words
Word by word diff instead of line by line.
Here is a sample of the output for git diff --color-words
:
If you want to do it without using jquery or modenizer you can use the code below:
(function(){
"use strict";
//shim for String's trim function..
function trim(string){
return string.trim ? string.trim() : string.replace(/^\s+|\s+$/g, "");
}
//returns whether the given element has the given class name..
function hasClassName(element, className){
//refactoring of Prototype's function..
var elClassName = element.className;
if(!elClassName)
return false;
var regex = new RegExp("(^|\\s)" + className + "(\\s|$)");
return regex.test(element.className);
}
function removeClassName(element, className){
//refactoring of Prototype's function..
var elClassName = element.className;
if(!elClassName)
return;
element.className = elClassName.replace(
new RegExp("(^|\\s+)" + className + "(\\s+|$)"), ' ');
}
function addClassName(element, className){
var elClassName = element.className;
if(elClassName)
element.className += " " + className;
else
element.className = className;
}
//strings to make event attachment x-browser..
var addEvent = document.addEventListener ?
'addEventListener' : 'attachEvent';
var eventPrefix = document.addEventListener ? '' : 'on';
//the class which is added when the placeholder is being used..
var placeHolderClassName = 'usingPlaceHolder';
//allows the given textField to use it's placeholder attribute
//as if it's functionality is supported natively..
window.placeHolder = function(textField){
//don't do anything if you get it for free..
if('placeholder' in document.createElement('input'))
return;
//don't do anything if the place holder attribute is not
//defined or is blank..
var placeHolder = textField.getAttribute('placeholder');
if(!placeHolder)
return;
//if it's just the empty string do nothing..
placeHolder = trim(placeHolder);
if(placeHolder === '')
return;
//called on blur - sets the value to the place holder if it's empty..
var onBlur = function(){
if(textField.value !== '') //a space is a valid input..
return;
textField.value = placeHolder;
addClassName(textField, placeHolderClassName);
};
//the blur event..
textField[addEvent](eventPrefix + 'blur', onBlur, false);
//the focus event - removes the place holder if required..
textField[addEvent](eventPrefix + 'focus', function(){
if(hasClassName(textField, placeHolderClassName)){
removeClassName(textField, placeHolderClassName);
textField.value = "";
}
}, false);
//the submit event on the form to which it's associated - if the
//placeholder is attached set the value to be empty..
var form = textField.form;
if(form){
form[addEvent](eventPrefix + 'submit', function(){
if(hasClassName(textField, placeHolderClassName))
textField.value = '';
}, false);
}
onBlur(); //call the onBlur to set it initially..
};
}());
For each text field you want to use it for you need to run placeHolder(HTMLInputElement)
, but I guess you can just change that to suit! Also, doing it this way, rather than just on load means that you can make it work for inputs which aren't in the DOM when the page loads.
Note, that this works by applying the class: usingPlaceHolder
to the input element, so you can use this to style it (e.g. add the rule .usingPlaceHolder { color: #999; font-style: italic; }
to make it look better).
Use the which function:
A <- c('a','a','b','b','b')
B <- c(1,0,1,1,0)
d <- data.frame(A, B)
r <- with(d, which(B==0, arr.ind=TRUE))
newd <- d[-r, ]
An example of fine-grained timing using mach_absolute_time()
in Swift 4:
let start = mach_absolute_time()
// do something
let elapsedMTU = mach_absolute_time() - start
var timebase = mach_timebase_info()
if mach_timebase_info(&timebase) == 0 {
let elapsed = Double(elapsedMTU) * Double(timebase.numer) / Double(timebase.denom)
print("render took \(elapsed)")
}
else {
print("timebase error")
}
If you are reluctant to change your existing code to std::array
, then use a couple of methods instead which takes non-type template arguments :
//Passed arrays store different data types
template <typename T, typename U, int size1, int size2>
bool equal(T (&arr1)[size1], U (&arr2)[size2] ){
return false;
}
//Passed arrays store SAME data types
template <typename T, int size1, int size2>
bool equal(T (&arr1)[size1], T (&arr2)[size2] ){
if(size1 == size2) {
for(int i = 0 ; i < size1; ++i){
if(arr1[i] != arr2[i]) return false;
}
return true;
}
return false;
}
Here is the demo. Note that, while calling, we just need to pass the array variables e.g. equal(iar1, iar2)
in your case, no need to pass the size of arrays.
If you use rs.next() you will move the cursor, than you should to move first() why don't check using first() directly?
public void fetchData(ResultSet res, JTable table) throws SQLException{
ResultSetMetaData metaData = res.getMetaData();
int fieldsCount = metaData.getColumnCount();
for (int i = 1; i <= fieldsCount; i++)
((DefaultTableModel) table.getModel()).addColumn(metaData.getColumnLabel(i));
if (!res.first())
JOptionPane.showMessageDialog(rootPane, "no data!");
else
do {
Vector<Object> v = new Vector<Object>();
for (int i = 1; i <= fieldsCount; i++)
v.addElement(res.getObject(i));
((DefaultTableModel) table.getModel()).addRow(v);
} while (res.next());
res.close();
}
You could use the @Consumes annotation to get the full body:
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.MediaType;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
@Path("doc")
public class BodyResource
{
@POST
@Consumes(MediaType.APPLICATION_XML)
public void post(Document doc) throws TransformerConfigurationException, TransformerException
{
Transformer tf = TransformerFactory.newInstance().newTransformer();
tf.transform(new DOMSource(doc), new StreamResult(System.out));
}
}
Note: Don't forget the "Content-Type: application/xml" header by the request.
To make a translation in the controller you could use $translate
service:
$translate(['COMMON.SI', 'COMMON.NO']).then(function (translations) {
vm.si = translations['COMMON.SI'];
vm.no = translations['COMMON.NO'];
});
That statement only does the translation on controller activation but it doesn't detect the runtime change in language. In order to achieve that behavior, you could listen the $rootScope
event: $translateChangeSuccess
and do the same translation there:
$rootScope.$on('$translateChangeSuccess', function () {
$translate(['COMMON.SI', 'COMMON.NO']).then(function (translations) {
vm.si = translations['COMMON.SI'];
vm.no = translations['COMMON.NO'];
});
});
Of course, you could encapsulate the $translate
service in a method and call it in the controller and in the $translateChangeSucess
listener.
What about CassandraDB, Project Voldemort, TokyoCabinet?
http://jsbin.com/ubalax/1/edit .You can see the results here
body {
position: relative;
float: left;
height: 3000px;
width: 100%;
}
body div {
position: absolute;
height: 100%;
width: 100%;
top:0;
left:0;
background-color: yellow;
}
It seems a lot of people get confused by the way objects are passed to functions and what passing by reference means. Object are still passed by value, it's just the value that is passed in PHP5 is a reference handle. As proof:
<?php
class Holder {
private $value;
public function __construct($value) {
$this->value = $value;
}
public function getValue() {
return $this->value;
}
}
function swap($x, $y) {
$tmp = $x;
$x = $y;
$y = $tmp;
}
$a = new Holder('a');
$b = new Holder('b');
swap($a, $b);
echo $a->getValue() . ", " . $b->getValue() . "\n";
Outputs:
a, b
To pass by reference means we can modify the variables that are seen by the caller, which clearly the code above does not do. We need to change the swap function to:
<?php
function swap(&$x, &$y) {
$tmp = $x;
$x = $y;
$y = $tmp;
}
$a = new Holder('a');
$b = new Holder('b');
swap($a, $b);
echo $a->getValue() . ", " . $b->getValue() . "\n";
Outputs:
b, a
in order to pass by reference.
Easily accomplished with a for
loop.
for (var i = 0; i < items.length; i++)
if (items[i] == 3452)
items[i] = 1010;
If you installed the command line tools separately, delete them using:
sudo rm -rf /Library/Developer/CommandLineTools
Just right click on the Visual Studio icon and then select "New Window" from the contextual toolbar that appears on the bottom in Windows 8. A new instance of Visual Studio will launch and then you can open your second project.
position: absolute
will position the element by coordinates, relative to the closest positioned ancestor, i.e. the closest parent which isn't position: static
.
Have your four divs nested inside the target div, give the target div position: relative
, and use position: absolute
on the others.
Structure your HTML similar to this:
<div id="container">
<div class="top left"></div>
<div class="top right"></div>
<div class="bottom left"></div>
<div class="bottom right"></div>
</div>
And this CSS should work:
#container {
position: relative;
}
#container > * {
position: absolute;
}
.left {
left: 0;
}
.right {
right: 0;
}
.top {
top: 0;
}
.bottom {
bottom: 0;
}
...
you can use this:
find . -name '* *' | while read fname
do
new_fname=`echo $fname | tr " " "_"`
if [ -e $new_fname ]
then
echo "File $new_fname already exists. Not replacing $fname"
else
echo "Creating new file $new_fname to replace $fname"
mv "$fname" $new_fname
fi
done
Fake loop that breaks on the first iteration:
$key = $value = NULL;
foreach ($array as $key => $value) {
break;
}
echo "$key = $value\n";
Or use each()
(warning: deprecated as of PHP 7.2.0):
reset($array);
list($key, $value) = each($array);
echo "$key = $value\n";
I use the following template in my projects:
angular.module("AppName.moduleName", [])
/**
* @ngdoc controller
* @name AppName.moduleName:ControllerNameController
* @description Describe what the controller is responsible for.
**/
.controller("ControllerNameController", function (dependencies) {
/* type */ $scope.modelName = null;
/* type */ $scope.modelName.modelProperty1 = null;
/* type */ $scope.modelName.modelPropertyX = null;
/* type */ var privateVariable1 = null;
/* type */ var privateVariableX = null;
(function init() {
// load data, init scope, etc.
})();
$scope.modelName.publicFunction1 = function () /* -> type */ {
// ...
};
$scope.modelName.publicFunctionX = function () /* -> type */ {
// ...
};
function privateFunction1() /* -> type */ {
// ...
}
function privateFunctionX() /* -> type */ {
// ...
}
});
"<name> <substring>"[/.*<([^>]*)/,1]
=> "substring"
No need to use scan
, if we need only one result.
No need to use Python's match
, when we have Ruby's String[regexp,#]
.
See: http://ruby-doc.org/core/String.html#method-i-5B-5D
Note: str[regexp, capture] ? new_str or nil
@Url.Action("Survey", "Applications", new { applicationid = @Model.ApplicationID }, protocol: Request.Url.Scheme)
You can use these solutions :
CSS rules applies to all tags that have following two classes :
.left.ui-class-selector {
/*style here*/
}
CSS rules applies to all tags that have <li>
with following two classes :
li.left.ui-class-selector {
/*style here*/
}
jQuery solution :
$("li.left.ui-class-selector").css("color", "red");
Javascript solution :
document.querySelector("li.left.ui-class-selector").style.color = "red";
The method to change the color, position and background color of toast is:
Toast toast=Toast.makeText(getApplicationContext(),"This is advanced toast",Toast.LENGTH_LONG);
toast.setGravity(Gravity.BOTTOM | Gravity.RIGHT,0,0);
View view=toast.getView();
TextView view1=(TextView)view.findViewById(android.R.id.message);
view1.setTextColor(Color.YELLOW);
view.setBackgroundResource(R.color.colorPrimary);
toast.show();
For line by line explanation: https://www.youtube.com/watch?v=5bzhGd1HZOc
class must be extend of AppCompatActivity to resolve the problem of setSuppertActionBar that is not recognizable
Just modified from the accepted answer above.
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
char *readFile(char *filename) {
FILE *f = fopen(filename, "rt");
assert(f);
fseek(f, 0, SEEK_END);
long length = ftell(f);
fseek(f, 0, SEEK_SET);
char *buffer = (char *) malloc(length + 1);
buffer[length] = '\0';
fread(buffer, 1, length, f);
fclose(f);
return buffer;
}
int main() {
char *content = readFile("../hello.txt");
printf("%s", content);
}
Following is a code snippet which splits a sentense to word and give its count too.
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class StringToword {
public static void main(String[] args) {
String s="a a a A A";
String[] splitedString=s.split(" ");
Map m=new HashMap();
int count=1;
for(String s1 :splitedString){
count=m.containsKey(s1)?count+1:1;
m.put(s1, count);
}
Iterator<StringToword> itr=m.entrySet().iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
If the SSL certificates are not properly installed in your system, you may get this error:
cURL error 60: SSL certificate problem: unable to get local issuer certificate.
You can solve this issue as follows:
Download a file with the updated list of certificates from https://curl.haxx.se/ca/cacert.pem
Move the downloaded cacert.pem
file to some safe location in your system
Update your php.ini
file and configure the path to that file:
Using the CellFormating event and the e argument:
If CInt(e.Value) < 5 Then e.CellStyle.ForeColor = Color.Red
THis is other method
You can also use setCenter
method with add new marker
check below code
$('#my_map').gmap3({
action: 'setCenter',
map:{
options:{
zoom: 10
}
},
marker:{
values:
[
{latLng:[position.coords.latitude, position.coords.longitude], data:"Netherlands !"}
]
}
});
You can try xml2js. It's a simple XML to JavaScript object converter. It gets your XML converted to a JS object so that you can access its content with ease.
Here are some other options:
I have used xml2js
and it has worked fine for me. The rest you might have to try out for yourself.
File "C:\pythonwork\readthefile080410.py", line 120, in medications_minimum3
counter[row[11]]+=1
TypeError: unhashable type: 'list'
row[11]
is unhashable. It's a list. That is precisely (and only) what the error message means. You might not like it, but that is the error message.
Do this
counter[tuple(row[11])]+=1
Also, simplify.
d= [ row for row in c if counter[tuple(row[11])]>=sample_cutoff ]
(Assuming you are not required to input the string from directly within Python code)
to get around the Issue Andrew Dalke pointed out, simply type the literal string into a text file and then use this;
input_ = '/directory_of_text_file/your_text_file.txt'
input_open = open(input_,'r+')
input_string = input_open.read()
print input_string
This will print the literal text of whatever is in the text file, even if it is;
' ''' """ “ \
Not fun or optimal, but can be useful, especially if you have 3 pages of code that would’ve needed character escaping.
You can also use copy con [filename] in a Windows command window (cmd.exe):
C:\copy con yourfile.txt [enter]
C:\CTRL + Z [enter] //hold CTRL key & press "Z" then press Enter key.
^Z
1 Files Copied.
This will create a file named yourfile.txt
in the local directory.
In my case, I achieved this with:
ALTER SEQUENCE table_tabl_id_seq RESTART WITH 6;
Where my table is named table
#multiple-background{_x000D_
box-sizing: border-box;_x000D_
width: 123px;_x000D_
height: 30px;_x000D_
font-size: 12pt;_x000D_
border-radius: 7px; _x000D_
background: url("https://cdn0.iconfinder.com/data/icons/woocons1/Checkbox%20Full.png"), linear-gradient(to bottom, #4ac425, #4ac425);_x000D_
background-repeat: no-repeat, repeat;_x000D_
background-position: 5px center, 0px 0px;_x000D_
background-size: 18px 18px, 100% 100%;_x000D_
color: white; _x000D_
border: 1px solid #e4f6df;_x000D_
box-shadow: .25px .25px .5px .5px black;_x000D_
padding: 3px 10px 0px 5px;_x000D_
text-align: right;_x000D_
}
_x000D_
<div id="multiple-background"> Completed </div>
_x000D_
It could be because of couple of Browser settings. Try with these options checked..
Tools > Internet Options > Advanced > Enable Integrated Windows Authentication (works with Integrated Windows Authentication set on IIS)
Tools > Internet Options> Security > Local Intranet > Custom Level > Automatic Logon
Worst case, try adding localhost to the Trusted sites.
If you are in a network, you can also try debugging by getting a network trace. Could be because of some proxy trying to authenticate.
While the rules in C++03 about when you need typename
and template
are largely reasonable, there is one annoying disadvantage of its formulation
template<typename T>
struct A {
typedef int result_type;
void f() {
// error, "this" is dependent, "template" keyword needed
this->g<float>();
// OK
g<float>();
// error, "A<T>" is dependent, "typename" keyword needed
A<T>::result_type n1;
// OK
result_type n2;
}
template<typename U>
void g();
};
As can be seen, we need the disambiguation keyword even if the compiler could perfectly figure out itself that A::result_type
can only be int
(and is hence a type), and this->g
can only be the member template g
declared later (even if A
is explicitly specialized somewhere, that would not affect the code within that template, so its meaning cannot be affected by a later specialization of A
!).
To improve the situation, in C++11 the language tracks when a type refers to the enclosing template. To know that, the type must have been formed by using a certain form of name, which is its own name (in the above, A
, A<T>
, ::A<T>
). A type referenced by such a name is known to be the current instantiation. There may be multiple types that are all the current instantiation if the type from which the name is formed is a member/nested class (then, A::NestedClass
and A
are both current instantiations).
Based on this notion, the language says that CurrentInstantiation::Foo
, Foo
and CurrentInstantiationTyped->Foo
(such as A *a = this; a->Foo
) are all member of the current instantiation if they are found to be members of a class that is the current instantiation or one of its non-dependent base classes (by just doing the name lookup immediately).
The keywords typename
and template
are now not required anymore if the qualifier is a member of the current instantiation. A keypoint here to remember is that A<T>
is still a type-dependent name (after all T
is also type dependent). But A<T>::result_type
is known to be a type - the compiler will "magically" look into this kind of dependent types to figure this out.
struct B {
typedef int result_type;
};
template<typename T>
struct C { }; // could be specialized!
template<typename T>
struct D : B, C<T> {
void f() {
// OK, member of current instantiation!
// A::result_type is not dependent: int
D::result_type r1;
// error, not a member of the current instantiation
D::questionable_type r2;
// OK for now - relying on C<T> to provide it
// But not a member of the current instantiation
typename D::questionable_type r3;
}
};
That's impressive, but can we do better? The language even goes further and requires that an implementation again looks up D::result_type
when instantiating D::f
(even if it found its meaning already at definition time). When now the lookup result differs or results in ambiguity, the program is ill-formed and a diagnostic must be given. Imagine what happens if we defined C
like this
template<>
struct C<int> {
typedef bool result_type;
typedef int questionable_type;
};
A compiler is required to catch the error when instantiating D<int>::f
. So you get the best of the two worlds: "Delayed" lookup protecting you if you could get in trouble with dependent base classes, and also "Immediate" lookup that frees you from typename
and template
.
In the code of D
, the name typename D::questionable_type
is not a member of the current instantiation. Instead the language marks it as a member of an unknown specialization. In particular, this is always the case when you are doing DependentTypeName::Foo
or DependentTypedName->Foo
and either the dependent type is not the current instantiation (in which case the compiler can give up and say "we will look later what Foo
is) or it is the current instantiation and the name was not found in it or its non-dependent base classes and there are also dependent base classes.
Imagine what happens if we had a member function h
within the above defined A
class template
void h() {
typename A<T>::questionable_type x;
}
In C++03, the language allowed to catch this error because there could never be a valid way to instantiate A<T>::h
(whatever argument you give to T
). In C++11, the language now has a further check to give more reason for compilers to implement this rule. Since A
has no dependent base classes, and A
declares no member questionable_type
, the name A<T>::questionable_type
is neither a member of the current instantiation nor a member of an unknown specialization. In that case, there should be no way that that code could validly compile at instantiation time, so the language forbids a name where the qualifier is the current instantiation to be neither a member of an unknown specialization nor a member of the current instantiation (however, this violation is still not required to be diagnosed).
You can try this knowledge on this answer and see whether the above definitions make sense for you on a real-world example (they are repeated slightly less detailed in that answer).
The C++11 rules make the following valid C++03 code ill-formed (which was not intended by the C++ committee, but will probably not be fixed)
struct B { void f(); };
struct A : virtual B { void f(); };
template<typename T>
struct C : virtual B, T {
void g() { this->f(); }
};
int main() {
C<A> c; c.g();
}
This valid C++03 code would bind this->f
to A::f
at instantiation time and everything is fine. C++11 however immediately binds it to B::f
and requires a double-check when instantiating, checking whether the lookup still matches. However when instantiating C<A>::g
, the Dominance Rule applies and lookup will find A::f
instead.
Similar situation for following configuration:
My solution:
I'd say that the main rule of thumb is not to roll your own. Try to use something that has been thoroughly tested, e.g., SHA-1 or something along those lines.
Simple, Effective and Efficient way to count row in HBASE:
Whenever you insert a row trigger this API which will increment that particular cell.
Htable.incrementColumnValue(Bytes.toBytes("count"), Bytes.toBytes("details"), Bytes.toBytes("count"), 1);
To check number of rows present in that table. Just use "Get" or "scan" API for that particular Row 'count'.
By using this Method you can get the row count in less than a millisecond.
You can use asyncio. (Documentation can be found here). It is used as a foundation for multiple Python asynchronous frameworks that provide high-performance network and web-servers, database connection libraries, distributed task queues, etc. Plus it has both high-level and low-level APIs to accomodate any kind of problem.
import asyncio
def background(f):
def wrapped(*args, **kwargs):
return asyncio.get_event_loop().run_in_executor(None, f, *args, **kwargs)
return wrapped
@background
def your_function(argument):
#code
Now this function will be run in parallel whenever called without putting main program into wait state. You can use it to parallelize for loop as well. When called for a for loop, though loop is sequential but every iteration runs in parallel to the main program as soon as interpreter gets there. For instance:
@background
def your_function(argument):
time.sleep(5)
print('function finished for '+str(argument))
for i in range(10):
your_function(i)
print('loop finished')
This produces following output:
loop finished
function finished for 4
function finished for 8
function finished for 0
function finished for 3
function finished for 6
function finished for 2
function finished for 5
function finished for 7
function finished for 9
function finished for 1
If you're in charge (or have any control over the web service), get them to add a unique root element!
If you can't change that at all, then you can do a bit of regex or string-splitting to parse each and pass each element to your XML Reader.
Alternatively, you could manually add a junk root element, by prefixing an opening tag and suffixing a closing tag.
You can get the port that is being used by an embedded Tomcat instance during tests by injecting the local.server.port value as such:
// Inject which port we were assigned
@Value("${local.server.port}")
int port;
Receiving a status 429 is not an error, it is the other server "kindly" asking you to please stop spamming requests. Obviously, your rate of requests has been too high and the server is not willing to accept this.
You should not seek to "dodge" this, or even try to circumvent server security settings by trying to spoof your IP, you should simply respect the server's answer by not sending too many requests.
If everything is set up properly, you will also have received a "Retry-after" header along with the 429 response. This header specifies the number of seconds you should wait before making another call. The proper way to deal with this "problem" is to read this header and to sleep your process for that many seconds.
You can find more information on status 429 here: http://tools.ietf.org/html/rfc6585#page-3
There's now a UITextField delegate method available on iOS13+
optional func textFieldDidChangeSelection(_ textField: UITextField)
No, you can't do it by using an actual <select>
, but there are techniques that allow you to "replace" them with javascript solutions that look better.
Here's a good article on the topic: <select> Something New
In Swift 3 try to use this code to get Key-Value Pair (tuple) at given index:
extension Dictionary {
subscript(i:Int) -> (key:Key,value:Value) {
get {
return self[index(startIndex, offsetBy: i)];
}
}
}
just add this code (Swift) . .
tableView.tableFooterView = UIView()
Libraries like underscore and lodash have a utility method called intersection
to find matches in arrays passed in. Take a look at: http://underscorejs.org/#intersection
In some cases we could have a couple of tables, and then we need to detect click just for particular table. My solution is this:
<table id="elitable" border="1" cellspacing="0" width="100%">
<tr>
<td>100</td><td>AAA</td><td>aaa</td>
</tr>
<tr>
<td>200</td><td>BBB</td><td>bbb</td>
</tr>
<tr>
<td>300</td><td>CCC</td><td>ccc</td>
</tr>
</table>
<script>
$(function(){
$("#elitable tr").click(function(){
alert (this.rowIndex);
});
});
</script>
This is a method of the java.awt.Component
class. It is used to set the position and size of a component:
setBounds
public void setBounds(int x, int y, int width, int height)
Moves and resizes this component. The new location of the top-left corner is specified by x and y, and the new size is specified by width and height. Parameters:
- x - the new x-coordinate of this component
- y - the new y-coordinate of this component
- width - the new width of this component
- height - the new height of this component
x
and y
as above correspond to the upper left corner in most (all?) cases.
It is a shortcut for setLocation
and setSize
.
This generally only works if the layout/layout manager are non-existent, i.e. null.
pageLoad = function () {
$('#div').unbind();
//jquery here
}
The pageLoad function is perfect for this case since it runs on the initial page load and every updatepanel async postback. I just had to add the unbind method to make the jquery work on updatepanel postbacks.
http://encosia.com/document-ready-and-pageload-are-not-the-same/
Try
\d \w |\d
or add a positive lookahead if you don't want to include the trailing space in the match
\d \w(?= )|\d
When you have two alternatives where one is an extension of the other, put the longer one first, otherwise it will have no opportunity to be matched.
There are a couple of ways:
If you want to use raw Javascript (without a helper like JQuery), then you could do something like:
var link = "http://google.com";
var element = document.createElement("a");
element.setAttribute("href", link);
element.innerHTML = "your text";
// and append it to where you'd like it to go:
document.body.appendChild(element);
The other method is to write the link directly into the document:
document.write("<a href='" + link + "'>" + text + "</a>");
This should work in SQL Server:
update ud
set assid = sale.assid
from sale
where sale.udid = id
It depends on the List
implementation. Since you index arrays with int
s, an ArrayList
can't hold more than Integer.MAX_VALUE
elements. A LinkedList
isn't limited in the same way, though, and can contain any amount of elements.
In [1]: import numpy as np
In [2]: a = np.array([[1, 2, 3], [4, 5, 6]])
In [3]: b = np.array([[9, 8, 7], [6, 5, 4]])
In [4]: np.concatenate((a, b))
Out[4]:
array([[1, 2, 3],
[4, 5, 6],
[9, 8, 7],
[6, 5, 4]])
or this:
In [1]: a = np.array([1, 2, 3])
In [2]: b = np.array([4, 5, 6])
In [3]: np.vstack((a, b))
Out[3]:
array([[1, 2, 3],
[4, 5, 6]])
It frees memory allocated to objects that are not being used by the program any more - hence the name "garbage". For example:
public static Object otherMethod(Object obj) {
return new Object();
}
public static void main(String[] args) {
Object myObj = new Object();
myObj = otherMethod(myObj);
// ... more code ...
}
I know this is extremely contrived, but here after you call otherMethod()
the original Object
created is made unreachable - and that's "garbage" that gets garbage collected.
In Java the GC runs automatically, but you can also call it explicitly with System.gc()
and try to force a major garbage collection. As Pascal Thivent points out, you really shouldn't have to do this and it might do more harm than good (see this question).
For more, see the wikipedia entry on Garbage collection and Tuning Garbage Collection (from Oracle)
I don't know, it works fine for me. Exact commands:
import scipy, pylab
ax = pylab.subplot(111)
ax.scatter(scipy.randn(100), scipy.randn(100), c='b')
ax.scatter(scipy.randn(100), scipy.randn(100), c='r')
ax.figure.show()
If you're working with a page in the Intranet Zone, you may find that IE9 no matter what you do, is going into IE7 Compat mode.
This is due to the setting within IE Compatibility settings which says that all Intranet sites should run in compatibility mode. You can untick this via a group policy (or just plain unticking it in IE), or you can set the following:
<meta http-equiv="X-UA-Compatible" content="IE=Edge" />
This works (as detailed in other answers), but may not initially appear so: it needs to come before the stylesheets are declared. If you don't, it is ignored.
If you're using ZLib in your project, then you need to find :
#if 1
in zconf.h and replace(uncomment) it with :
#if HAVE_UNISTD_H /* ...the rest of the line
If it isn't ZLib I guess you should find some alternative way to do this. GL.
NOTE: The following is likely highly contextual and time-limited before the switch/general availability of macos Catalina 10.15. New laptop. I am writing this Oct 1st, 2019.
These specific circumstances are, I believe, what caused build problems for me. They may not apply in most other cases.
macos 10.14.6 Mojave, Xcode 11.0, right before the launch of macos Catalina 10.15. Newly purchased Macbook Pro.
failure on pip install psycopg2
, which is, basically, a Python package getting compiled from source.
I have already carried out a number of the suggested adjustments in the answers given here.
pip install psycopg2
Collecting psycopg2
Using cached https://files.pythonhosted.org/packages/5c/1c/6997288da181277a0c29bc39a5f9143ff20b8c99f2a7d059cfb55163e165/psycopg2-2.8.3.tar.gz
Installing collected packages: psycopg2
Running setup.py install for psycopg2 ... error
ERROR: Command errored out with exit status 1:
command: xxxx/venv/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/bk/_1cwm6dj3h1c0ptrhvr2v7dc0000gs/T/pip-install-z0qca56g/psycopg2/setup.py'"'"'; __file__='"'"'/private/var/folders/bk/_1cwm6dj3h1c0ptrhvr2v7dc0000gs/T/pip-install-z0qca56g/psycopg2/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /private/var/folders/bk/_1cwm6dj3h1c0ptrhvr2v7dc0000gs/T/pip-record-ef126d8d/install-record.txt --single-version-externally-managed --compile --install-headers xxx/venv/include/site/python3.6/psycopg2
...
/usr/bin/clang -Wno-unused-result -Wsign-compare -Wunreachable-code -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -pipe -Os -isysroot/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk -DPSYCOPG_VERSION=2.8.3 (dt dec pq3 ext lo64) -DPG_VERSION_NUM=90615 -DHAVE_LO64=1 -I/Users/jluc/kds2/py2/venv/include -I/opt/local/Library/Frameworks/Python.framework/Versions/3.6/include/python3.6m -I. -I/opt/local/include/postgresql96 -I/opt/local/include/postgresql96/server -c psycopg/psycopgmodule.c -o build/temp.macosx-10.14-x86_64-3.6/psycopg/psycopgmodule.o
clang: warning: no such sysroot directory:
'/Applications/Xcode.app/Contents/Developer/Platforms
?the real error?
/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk' [-Wmissing-sysroot]
In file included from psycopg/psycopgmodule.c:27:
In file included from ./psycopg/psycopg.h:34:
/opt/local/Library/Frameworks/Python.framework/Versions/3.6/include/python3.6m/Python.h:25:10: fatal error: 'stdio.h' file not found
? what I thought was the error ?
#include <stdio.h>
^~~~~~~~~
1 error generated.
It appears you are missing some prerequisite to build the package
xcode-select --install
open /Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg
Still the same error on stdio.h.
which exists in a number of places:
(venv) jluc@bemyerp$ mdfind -name stdio.h
/System/Library/Frameworks/Kernel.framework/Versions/A/Headers/sys/stdio.h
/usr/include/_stdio.h
/usr/include/secure/_stdio.h
/usr/include/stdio.h ? I believe this is the one that's usually missing.
but I have it.
/usr/include/sys/stdio.h
/usr/include/xlocale/_stdio.h
clang
is complaining about and look:(venv) jluc@gotchas$ cd /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs
(venv) jluc@SDKs$ ls -l
total 0
drwxr-xr-x 8 root wheel 256 Aug 29 23:47 MacOSX.sdk
drwxr-xr-x 4 root wheel 128 Aug 29 23:47 DriverKit19.0.sdk
drwxr-xr-x 6 root wheel 192 Sep 11 04:47 ..
lrwxr-xr-x 1 root wheel 10 Oct 1 13:28 MacOSX10.15.sdk -> MacOSX.sdk
drwxr-xr-x 5 root wheel 160 Oct 1 13:34 .
Hah, we have a symlink for MacOSX10.15.sdk, but none for MacOSX10.14.sdk. Here's my first clang
error again:
clang: warning: no such sysroot directory: '/Applications/Xcode.app/.../Developer/SDKs/MacOSX10.14.sdk' [-Wmissing-sysroot]
My guess is Apple jumped the gun on their xcode config and are already thinking they're on Catalina. Since it's a new Mac, the old config for 10.14 is not in place.
Let's symlink 10.14 the same way as 10.15:
ln -s MacOSX.sdk/ MacOSX10.14.sdk
btw, if I go to that sdk directory, I find:
...
./usr/include/sys/stdio.h
./usr/include/stdio.h
....
pip install psycopg2
works.
Note: the actual pip install command made no reference to MacOSX10.14.sdk, that came at a later point, possibly by the Python installation mechanism introspecting the OS version.
I often use this workaround in CLI where instead of configuring my .gitignore
, I create a separate .include
file where I define the (sub)directories I want included in spite of directories directly or recursively ignored by .gitignore
.
Thus, I additionally use
git add `cat .include`
during staging, before committing.
To the OP, I suggest using a .include
which has these lines:
<parent_folder_path>/application/language/gr/*
NOTE: Using cat
does not allow usage of aliases (within .include
) for specifying $HOME (or any other specific directory). This is because the line homedir/app1/*
when passed to git add
using the above command appears as git add 'homedir/app1/*'
, and enclosing characters in single quotes ('') preserves the literal value of each character within the quotes, thus preventing aliases (such as homedir) from functioning (see Bash Single Quotes).
Here is an example of a .include
file I use in my repo here.
/home/abhirup/token.txt
/home/abhirup/.include
/home/abhirup/.vim/*
/home/abhirup/.viminfo
/home/abhirup/.bashrc
/home/abhirup/.vimrc
/home/abhirup/.condarc
Consider the limitations of the different Load*
methods. From the MSDN docs...
LoadFile does not load files into the LoadFrom context, and does not resolve dependencies using the load path, as the LoadFrom method does.
More information on Load Contexts can be found in the LoadFrom
docs.
For Each I As Item In Items
If I = x Then Continue For
' Do something
Next
The mock
module is basically made for that.
import mock
obj = mock.Mock()
obj.a = 5
What about
DT <- data.table(test)
setkey(DT, id)
DT[J(unique(id)), mult = "first"]
There is also a unique method for data.tables
which will return the the first row by key
jdtu <- function() unique(DT)
I think, if you are ordering test
outside the benchmark, then you can removing the setkey
and data.table
conversion from the benchmark as well (as the setkey basically sorts by id, the same as order
).
set.seed(21)
test <- data.frame(id=sample(1e3, 1e5, TRUE), string=sample(LETTERS, 1e5, TRUE))
test <- test[order(test$id), ]
DT <- data.table(DT, key = 'id')
ju <- function() test[!duplicated(test$id),]
jdt <- function() DT[J(unique(id)),mult = 'first']
library(rbenchmark)
benchmark(ju(), jdt(), replications = 5)
## test replications elapsed relative user.self sys.self
## 2 jdt() 5 0.01 1 0.02 0
## 1 ju() 5 0.05 5 0.05 0
and with more data
** Edit with unique method**
set.seed(21)
test <- data.frame(id=sample(1e4, 1e6, TRUE), string=sample(LETTERS, 1e6, TRUE))
test <- test[order(test$id), ]
DT <- data.table(test, key = 'id')
test replications elapsed relative user.self sys.self
2 jdt() 5 0.09 2.25 0.09 0.00
3 jdtu() 5 0.04 1.00 0.05 0.00
1 ju() 5 0.22 5.50 0.19 0.03
The unique method is fastest here.
$argv[0]; // the script name
$argv[1]; // the first parameter
$argv[2]; // the second parameter
If you want to all the script to run regardless of where you call it from (command line or from the browser) you'll want something like the following:
<?php
if ($_GET) {
$argument1 = $_GET['argument1'];
$argument2 = $_GET['argument2'];
} else {
$argument1 = $argv[1];
$argument2 = $argv[2];
}
?>
To call from command line chmod 755 /var/www/webroot/index.php
and use
/usr/bin/php /var/www/webroot/index.php arg1 arg2
To call from the browser, use
http://www.mydomain.com/index.php?argument1=arg1&argument2=arg2
You can also use the special word like
:
Public Sub Search()
If "My Big String with, in the middle" Like "*,*" Then
Debug.Print ("Found ','")
End If
End Sub
I know this is an old post but I recently ran into a very similar problem. Unfortunately I wasn't able to use any of the alter database commands because an exclusive lock couldn't be placed. But I was never able to find an open connection to the db. I eventually had to forcefully delete the health state of the database to force it into a restoring state instead of in recovery.
EDIT: http://jsfiddle.net/nCFGL/223/ My Example.
You should be able to like follows:
var pieData = [{
value: 30,
color: "#F38630",
label: 'Sleep',
labelColor: 'white',
labelFontSize: '16'
},
...
];
Include the Chart.js located at:
>>> sys.stdout.write(1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: expected a string or other character buffer object
>>> sys.stdout.write("a")
a>>> sys.stdout.write("a") ; print(1)
a1
Observing the example above:
sys.stdout.write
won't write non-string object, but print
will
sys.stdout.write
won't add a new line symbol in the end, but print
will
If we dive deeply,
sys.stdout
is a file object which can be used for the output of print()
if file argument of print()
is not specified, sys.stdout
will be used
There is a workaround using Web Server for Chrome.
Here are the steps:
Now easily access your local file:
function run(){
// 8887 is the port number you have launched your serve
var URL = "http://127.0.0.1:8887/002.jpg";
window.open(URL, null);
}
run();
PS: You might need to select the CORS Header option from advanced setting incase you face any cross origin access error.
I find another way of doing the same thing by using @PathParam
. Here is the code sample.
@GET
@Path("data/xml/{Ids}")
@Produces("application/xml")
public Object getData(@PathParam("zrssIds") String Ids)
{
System.out.println("zrssIds = " + Ids);
//Here you need to use String tokenizer to make the array from the string.
}
Call the service by using following url.
http://localhost:8080/MyServices/resources/cm/data/xml/12,13,56,76
where
http://localhost:8080/[War File Name]/[Servlet Mapping]/[Class Path]/data/xml/12,13,56,76
Try this :
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
public class FragmentOne extends Fragment{
View rootView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_one, container, false);
Button button = (Button) rootView.findViewById(R.id.buttonSayHi);
button.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
onButtonClicked(v);
}
});
return rootView;
}
public void onButtonClicked(View view)
{
//do your stuff here..
final FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.frameLayoutFragmentContainer, new FragmentTwo(), "NewFragmentTag");
ft.commit();
ft.addToBackStack(null);
}
}
check this : click here
Following jrub post on May 4 '2015, I'm adding updated locale list. Executed on a Nexus 6P with Android 7.0 Nougat and English US locale.
af_ [Afrikaans]
af_NA [Afrikaans (Namibia)]
af_ZA [Afrikaans (South Africa)]
agq_ [Aghem]
agq_CM [Aghem (Cameroon)]
ak_ [Akan]
ak_GH [Akan (Ghana)]
am_ [Amharic]
am_ET [Amharic (Ethiopia)]
ar_ [Arabic]
ar_001 [Arabic (World)]
ar_AE [Arabic (United Arab Emirates)]
ar_BH [Arabic (Bahrain)]
ar_DJ [Arabic (Djibouti)]
ar_DZ [Arabic (Algeria)]
ar_EG [Arabic (Egypt)]
ar_EH [Arabic (Western Sahara)]
ar_ER [Arabic (Eritrea)]
ar_IL [Arabic (Israel)]
ar_IQ [Arabic (Iraq)]
ar_JO [Arabic (Jordan)]
ar_KM [Arabic (Comoros)]
ar_KW [Arabic (Kuwait)]
ar_LB [Arabic (Lebanon)]
ar_LY [Arabic (Libya)]
ar_MA [Arabic (Morocco)]
ar_MR [Arabic (Mauritania)]
ar_OM [Arabic (Oman)]
ar_PS [Arabic (Palestine)]
ar_QA [Arabic (Qatar)]
ar_SA [Arabic (Saudi Arabia)]
ar_SD [Arabic (Sudan)]
ar_SO [Arabic (Somalia)]
ar_SS [Arabic (South Sudan)]
ar_SY [Arabic (Syria)]
ar_TD [Arabic (Chad)]
ar_TN [Arabic (Tunisia)]
ar_YE [Arabic (Yemen)]
as_ [Assamese]
as_IN [Assamese (India)]
asa_ [Asu]
asa_TZ [Asu (Tanzania)]
az_ [Azerbaijani (Cyrillic)]
az_ [Azerbaijani (Latin)]
az_ [Azerbaijani]
az_AZ [Azerbaijani (Cyrillic,Azerbaijan)]
az_AZ [Azerbaijani (Latin,Azerbaijan)]
bas_ [Basaa]
bas_CM [Basaa (Cameroon)]
be_ [Belarusian]
be_BY [Belarusian (Belarus)]
bem_ [Bemba]
bem_ZM [Bemba (Zambia)]
bez_ [Bena]
bez_TZ [Bena (Tanzania)]
bg_ [Bulgarian]
bg_BG [Bulgarian (Bulgaria)]
bm_ [Bambara]
bm_ML [Bambara (Mali)]
bn_ [Bengali]
bn_BD [Bengali (Bangladesh)]
bn_IN [Bengali (India)]
bo_ [Tibetan]
bo_CN [Tibetan (China)]
bo_IN [Tibetan (India)]
br_ [Breton]
br_FR [Breton (France)]
brx_ [Bodo]
brx_IN [Bodo (India)]
bs_ [Bosnian (Cyrillic)]
bs_ [Bosnian (Latin)]
bs_ [Bosnian]
bs_BA [Bosnian (Cyrillic,Bosnia & Herzegovina)]
bs_BA [Bosnian (Latin,Bosnia & Herzegovina)]
ca_ [Catalan]
ca_AD [Catalan (Andorra)]
ca_ES [Catalan (Spain)]
ca_FR [Catalan (France)]
ca_IT [Catalan (Italy)]
ce_ [Chechen]
ce_RU [Chechen (Russia)]
cgg_ [Chiga]
cgg_UG [Chiga (Uganda)]
chr_ [Cherokee]
chr_US [Cherokee (United States)]
cs_ [Czech]
cs_CZ [Czech (Czech Republic)]
cy_ [Welsh]
cy_GB [Welsh (United Kingdom)]
da_ [Danish]
da_DK [Danish (Denmark)]
da_GL [Danish (Greenland)]
dav_ [Taita]
dav_KE [Taita (Kenya)]
de_ [German]
de_AT [German (Austria)]
de_BE [German (Belgium)]
de_CH [German (Switzerland)]
de_DE [German (Germany)]
de_LI [German (Liechtenstein)]
de_LU [German (Luxembourg)]
dje_ [Zarma]
dje_NE [Zarma (Niger)]
dsb_ [Lower Sorbian]
dsb_DE [Lower Sorbian (Germany)]
dua_ [Duala]
dua_CM [Duala (Cameroon)]
dyo_ [Jola-Fonyi]
dyo_SN [Jola-Fonyi (Senegal)]
dz_ [Dzongkha]
dz_BT [Dzongkha (Bhutan)]
ebu_ [Embu]
ebu_KE [Embu (Kenya)]
ee_ [Ewe]
ee_GH [Ewe (Ghana)]
ee_TG [Ewe (Togo)]
el_ [Greek]
el_CY [Greek (Cyprus)]
el_GR [Greek (Greece)]
en_ [English]
en_001 [English (World)]
en_150 [English (Europe)]
en_AG [English (Antigua & Barbuda)]
en_AI [English (Anguilla)]
en_AS [English (American Samoa)]
en_AT [English (Austria)]
en_AU [English (Australia)]
en_BB [English (Barbados)]
en_BE [English (Belgium)]
en_BI [English (Burundi)]
en_BM [English (Bermuda)]
en_BS [English (Bahamas)]
en_BW [English (Botswana)]
en_BZ [English (Belize)]
en_CA [English (Canada)]
en_CC [English (Cocos (Keeling) Islands)]
en_CH [English (Switzerland)]
en_CK [English (Cook Islands)]
en_CM [English (Cameroon)]
en_CX [English (Christmas Island)]
en_CY [English (Cyprus)]
en_DE [English (Germany)]
en_DG [English (Diego Garcia)]
en_DK [English (Denmark)]
en_DM [English (Dominica)]
en_ER [English (Eritrea)]
en_FI [English (Finland)]
en_FJ [English (Fiji)]
en_FK [English (Falkland Islands (Islas Malvinas))]
en_FM [English (Micronesia)]
en_GB [English (United Kingdom)]
en_GD [English (Grenada)]
en_GG [English (Guernsey)]
en_GH [English (Ghana)]
en_GI [English (Gibraltar)]
en_GM [English (Gambia)]
en_GU [English (Guam)]
en_GY [English (Guyana)]
en_HK [English (Hong Kong)]
en_IE [English (Ireland)]
en_IL [English (Israel)]
en_IM [English (Isle of Man)]
en_IN [English (India)]
en_IO [English (British Indian Ocean Territory)]
en_JE [English (Jersey)]
en_JM [English (Jamaica)]
en_KE [English (Kenya)]
en_KI [English (Kiribati)]
en_KN [English (St. Kitts & Nevis)]
en_KY [English (Cayman Islands)]
en_LC [English (St. Lucia)]
en_LR [English (Liberia)]
en_LS [English (Lesotho)]
en_MG [English (Madagascar)]
en_MH [English (Marshall Islands)]
en_MO [English (Macau)]
en_MP [English (Northern Mariana Islands)]
en_MS [English (Montserrat)]
en_MT [English (Malta)]
en_MU [English (Mauritius)]
en_MW [English (Malawi)]
en_MY [English (Malaysia)]
en_NA [English (Namibia)]
en_NF [English (Norfolk Island)]
en_NG [English (Nigeria)]
en_NL [English (Netherlands)]
en_NR [English (Nauru)]
en_NU [English (Niue)]
en_NZ [English (New Zealand)]
en_PG [English (Papua New Guinea)]
en_PH [English (Philippines)]
en_PK [English (Pakistan)]
en_PN [English (Pitcairn Islands)]
en_PR [English (Puerto Rico)]
en_PW [English (Palau)]
en_RW [English (Rwanda)]
en_SB [English (Solomon Islands)]
en_SC [English (Seychelles)]
en_SD [English (Sudan)]
en_SE [English (Sweden)]
en_SG [English (Singapore)]
en_SH [English (St. Helena)]
en_SI [English (Slovenia)]
en_SL [English (Sierra Leone)]
en_SS [English (South Sudan)]
en_SX [English (Sint Maarten)]
en_SZ [English (Swaziland)]
en_TC [English (Turks & Caicos Islands)]
en_TK [English (Tokelau)]
en_TO [English (Tonga)]
en_TT [English (Trinidad & Tobago)]
en_TV [English (Tuvalu)]
en_TZ [English (Tanzania)]
en_UG [English (Uganda)]
en_UM [English (U.S. Outlying Islands)]
en_US [English (United States)]
en_US [English (United States,Computer)]
en_VC [English (St. Vincent & Grenadines)]
en_VG [English (British Virgin Islands)]
en_VI [English (U.S. Virgin Islands)]
en_VU [English (Vanuatu)]
en_WS [English (Samoa)]
en_ZA [English (South Africa)]
en_ZM [English (Zambia)]
en_ZW [English (Zimbabwe)]
eo_ [Esperanto]
es_ [Spanish]
es_419 [Spanish (Latin America)]
es_AR [Spanish (Argentina)]
es_BO [Spanish (Bolivia)]
es_CL [Spanish (Chile)]
es_CO [Spanish (Colombia)]
es_CR [Spanish (Costa Rica)]
es_CU [Spanish (Cuba)]
es_DO [Spanish (Dominican Republic)]
es_EA [Spanish (Ceuta & Melilla)]
es_EC [Spanish (Ecuador)]
es_ES [Spanish (Spain)]
es_GQ [Spanish (Equatorial Guinea)]
es_GT [Spanish (Guatemala)]
es_HN [Spanish (Honduras)]
es_IC [Spanish (Canary Islands)]
es_MX [Spanish (Mexico)]
es_NI [Spanish (Nicaragua)]
es_PA [Spanish (Panama)]
es_PE [Spanish (Peru)]
es_PH [Spanish (Philippines)]
es_PR [Spanish (Puerto Rico)]
es_PY [Spanish (Paraguay)]
es_SV [Spanish (El Salvador)]
es_US [Spanish (United States)]
es_UY [Spanish (Uruguay)]
es_VE [Spanish (Venezuela)]
et_ [Estonian]
et_EE [Estonian (Estonia)]
eu_ [Basque]
eu_ES [Basque (Spain)]
ewo_ [Ewondo]
ewo_CM [Ewondo (Cameroon)]
fa_ [Persian]
fa_AF [Persian (Afghanistan)]
fa_IR [Persian (Iran)]
ff_ [Fulah]
ff_CM [Fulah (Cameroon)]
ff_GN [Fulah (Guinea)]
ff_MR [Fulah (Mauritania)]
ff_SN [Fulah (Senegal)]
fi_ [Finnish]
fi_FI [Finnish (Finland)]
fil_ [Filipino]
fil_PH [Filipino (Philippines)]
fo_ [Faroese]
fo_DK [Faroese (Denmark)]
fo_FO [Faroese (Faroe Islands)]
fr_ [French]
fr_BE [French (Belgium)]
fr_BF [French (Burkina Faso)]
fr_BI [French (Burundi)]
fr_BJ [French (Benin)]
fr_BL [French (St. Barthélemy)]
fr_CA [French (Canada)]
fr_CD [French (Congo (DRC))]
fr_CF [French (Central African Republic)]
fr_CG [French (Congo (Republic))]
fr_CH [French (Switzerland)]
fr_CI [French (Côte d’Ivoire)]
fr_CM [French (Cameroon)]
fr_DJ [French (Djibouti)]
fr_DZ [French (Algeria)]
fr_FR [French (France)]
fr_GA [French (Gabon)]
fr_GF [French (French Guiana)]
fr_GN [French (Guinea)]
fr_GP [French (Guadeloupe)]
fr_GQ [French (Equatorial Guinea)]
fr_HT [French (Haiti)]
fr_KM [French (Comoros)]
fr_LU [French (Luxembourg)]
fr_MA [French (Morocco)]
fr_MC [French (Monaco)]
fr_MF [French (St. Martin)]
fr_MG [French (Madagascar)]
fr_ML [French (Mali)]
fr_MQ [French (Martinique)]
fr_MR [French (Mauritania)]
fr_MU [French (Mauritius)]
fr_NC [French (New Caledonia)]
fr_NE [French (Niger)]
fr_PF [French (French Polynesia)]
fr_PM [French (St. Pierre & Miquelon)]
fr_RE [French (Réunion)]
fr_RW [French (Rwanda)]
fr_SC [French (Seychelles)]
fr_SN [French (Senegal)]
fr_SY [French (Syria)]
fr_TD [French (Chad)]
fr_TG [French (Togo)]
fr_TN [French (Tunisia)]
fr_VU [French (Vanuatu)]
fr_WF [French (Wallis & Futuna)]
fr_YT [French (Mayotte)]
fur_ [Friulian]
fur_IT [Friulian (Italy)]
fy_ [Western Frisian]
fy_NL [Western Frisian (Netherlands)]
ga_ [Irish]
ga_IE [Irish (Ireland)]
gd_ [Scottish Gaelic]
gd_GB [Scottish Gaelic (United Kingdom)]
gl_ [Galician]
gl_ES [Galician (Spain)]
gsw_ [Swiss German]
gsw_CH [Swiss German (Switzerland)]
gsw_FR [Swiss German (France)]
gsw_LI [Swiss German (Liechtenstein)]
gu_ [Gujarati]
gu_IN [Gujarati (India)]
guz_ [Gusii]
guz_KE [Gusii (Kenya)]
gv_ [Manx]
gv_IM [Manx (Isle of Man)]
ha_ [Hausa]
ha_GH [Hausa (Ghana)]
ha_NE [Hausa (Niger)]
ha_NG [Hausa (Nigeria)]
haw_ [Hawaiian]
haw_US [Hawaiian (United States)]
hi_ [Hindi]
hi_IN [Hindi (India)]
hr_ [Croatian]
hr_BA [Croatian (Bosnia & Herzegovina)]
hr_HR [Croatian (Croatia)]
hsb_ [Upper Sorbian]
hsb_DE [Upper Sorbian (Germany)]
hu_ [Hungarian]
hu_HU [Hungarian (Hungary)]
hy_ [Armenian]
hy_AM [Armenian (Armenia)]
ig_ [Igbo]
ig_NG [Igbo (Nigeria)]
ii_ [Sichuan Yi]
ii_CN [Sichuan Yi (China)]
in_ [Indonesian]
in_ID [Indonesian (Indonesia)]
is_ [Icelandic]
is_IS [Icelandic (Iceland)]
it_ [Italian]
it_CH [Italian (Switzerland)]
it_IT [Italian (Italy)]
it_SM [Italian (San Marino)]
iw_ [Hebrew]
iw_IL [Hebrew (Israel)]
ja_ [Japanese]
ja_JP [Japanese (Japan)]
jgo_ [Ngomba]
jgo_CM [Ngomba (Cameroon)]
ji_ [Yiddish]
ji_001 [Yiddish (World)]
jmc_ [Machame]
jmc_TZ [Machame (Tanzania)]
ka_ [Georgian]
ka_GE [Georgian (Georgia)]
kab_ [Kabyle]
kab_DZ [Kabyle (Algeria)]
kam_ [Kamba]
kam_KE [Kamba (Kenya)]
kde_ [Makonde]
kde_TZ [Makonde (Tanzania)]
kea_ [Kabuverdianu]
kea_CV [Kabuverdianu (Cape Verde)]
khq_ [Koyra Chiini]
khq_ML [Koyra Chiini (Mali)]
ki_ [Kikuyu]
ki_KE [Kikuyu (Kenya)]
kk_ [Kazakh]
kk_KZ [Kazakh (Kazakhstan)]
kkj_ [Kako]
kkj_CM [Kako (Cameroon)]
kl_ [Kalaallisut]
kl_GL [Kalaallisut (Greenland)]
kln_ [Kalenjin]
kln_KE [Kalenjin (Kenya)]
km_ [Khmer]
km_KH [Khmer (Cambodia)]
kn_ [Kannada]
kn_IN [Kannada (India)]
ko_ [Korean]
ko_KP [Korean (North Korea)]
ko_KR [Korean (South Korea)]
kok_ [Konkani]
kok_IN [Konkani (India)]
ks_ [Kashmiri]
ks_IN [Kashmiri (India)]
ksb_ [Shambala]
ksb_TZ [Shambala (Tanzania)]
ksf_ [Bafia]
ksf_CM [Bafia (Cameroon)]
ksh_ [Colognian]
ksh_DE [Colognian (Germany)]
kw_ [Cornish]
kw_GB [Cornish (United Kingdom)]
ky_ [Kyrgyz]
ky_KG [Kyrgyz (Kyrgyzstan)]
lag_ [Langi]
lag_TZ [Langi (Tanzania)]
lb_ [Luxembourgish]
lb_LU [Luxembourgish (Luxembourg)]
lg_ [Ganda]
lg_UG [Ganda (Uganda)]
lkt_ [Lakota]
lkt_US [Lakota (United States)]
ln_ [Lingala]
ln_AO [Lingala (Angola)]
ln_CD [Lingala (Congo (DRC))]
ln_CF [Lingala (Central African Republic)]
ln_CG [Lingala (Congo (Republic))]
lo_ [Lao]
lo_LA [Lao (Laos)]
lrc_ [Northern Luri]
lrc_IQ [Northern Luri (Iraq)]
lrc_IR [Northern Luri (Iran)]
lt_ [Lithuanian]
lt_LT [Lithuanian (Lithuania)]
lu_ [Luba-Katanga]
lu_CD [Luba-Katanga (Congo (DRC))]
luo_ [Luo]
luo_KE [Luo (Kenya)]
luy_ [Luyia]
luy_KE [Luyia (Kenya)]
lv_ [Latvian]
lv_LV [Latvian (Latvia)]
mas_ [Masai]
mas_KE [Masai (Kenya)]
mas_TZ [Masai (Tanzania)]
mer_ [Meru]
mer_KE [Meru (Kenya)]
mfe_ [Morisyen]
mfe_MU [Morisyen (Mauritius)]
mg_ [Malagasy]
mg_MG [Malagasy (Madagascar)]
mgh_ [Makhuwa-Meetto]
mgh_MZ [Makhuwa-Meetto (Mozambique)]
mgo_ [Meta']
mgo_CM [Meta' (Cameroon)]
mk_ [Macedonian]
mk_MK [Macedonian (Macedonia (FYROM))]
ml_ [Malayalam]
ml_IN [Malayalam (India)]
mn_ [Mongolian]
mn_MN [Mongolian (Mongolia)]
mr_ [Marathi]
mr_IN [Marathi (India)]
ms_ [Malay]
ms_BN [Malay (Brunei)]
ms_MY [Malay (Malaysia)]
ms_SG [Malay (Singapore)]
mt_ [Maltese]
mt_MT [Maltese (Malta)]
mua_ [Mundang]
mua_CM [Mundang (Cameroon)]
my_ [Burmese]
my_MM [Burmese (Myanmar (Burma))]
mzn_ [Mazanderani]
mzn_IR [Mazanderani (Iran)]
naq_ [Nama]
naq_NA [Nama (Namibia)]
nb_ [Norwegian Bokmål]
nb_NO [Norwegian Bokmål (Norway)]
nb_SJ [Norwegian Bokmål (Svalbard & Jan Mayen)]
nd_ [North Ndebele]
nd_ZW [North Ndebele (Zimbabwe)]
ne_ [Nepali]
ne_IN [Nepali (India)]
ne_NP [Nepali (Nepal)]
nl_ [Dutch]
nl_AW [Dutch (Aruba)]
nl_BE [Dutch (Belgium)]
nl_BQ [Dutch (Caribbean Netherlands)]
nl_CW [Dutch (Curaçao)]
nl_NL [Dutch (Netherlands)]
nl_SR [Dutch (Suriname)]
nl_SX [Dutch (Sint Maarten)]
nmg_ [Kwasio]
nmg_CM [Kwasio (Cameroon)]
nn_ [Norwegian Nynorsk]
nn_NO [Norwegian Nynorsk (Norway)]
nnh_ [Ngiemboon]
nnh_CM [Ngiemboon (Cameroon)]
nus_ [Nuer]
nus_SS [Nuer (South Sudan)]
nyn_ [Nyankole]
nyn_UG [Nyankole (Uganda)]
om_ [Oromo]
om_ET [Oromo (Ethiopia)]
om_KE [Oromo (Kenya)]
or_ [Oriya]
or_IN [Oriya (India)]
os_ [Ossetic]
os_GE [Ossetic (Georgia)]
os_RU [Ossetic (Russia)]
pa_ [Punjabi (Arabic)]
pa_ [Punjabi (Gurmukhi)]
pa_ [Punjabi]
pa_IN [Punjabi (Gurmukhi,India)]
pa_PK [Punjabi (Arabic,Pakistan)]
pl_ [Polish]
pl_PL [Polish (Poland)]
ps_ [Pashto]
ps_AF [Pashto (Afghanistan)]
pt_ [Portuguese]
pt_AO [Portuguese (Angola)]
pt_BR [Portuguese (Brazil)]
pt_CV [Portuguese (Cape Verde)]
pt_GW [Portuguese (Guinea-Bissau)]
pt_MO [Portuguese (Macau)]
pt_MZ [Portuguese (Mozambique)]
pt_PT [Portuguese (Portugal)]
pt_ST [Portuguese (São Tomé & Príncipe)]
pt_TL [Portuguese (Timor-Leste)]
qu_ [Quechua]
qu_BO [Quechua (Bolivia)]
qu_EC [Quechua (Ecuador)]
qu_PE [Quechua (Peru)]
rm_ [Romansh]
rm_CH [Romansh (Switzerland)]
rn_ [Rundi]
rn_BI [Rundi (Burundi)]
ro_ [Romanian]
ro_MD [Romanian (Moldova)]
ro_RO [Romanian (Romania)]
rof_ [Rombo]
rof_TZ [Rombo (Tanzania)]
ru_ [Russian]
ru_BY [Russian (Belarus)]
ru_KG [Russian (Kyrgyzstan)]
ru_KZ [Russian (Kazakhstan)]
ru_MD [Russian (Moldova)]
ru_RU [Russian (Russia)]
ru_UA [Russian (Ukraine)]
rw_ [Kinyarwanda]
rw_RW [Kinyarwanda (Rwanda)]
rwk_ [Rwa]
rwk_TZ [Rwa (Tanzania)]
sah_ [Sakha]
sah_RU [Sakha (Russia)]
saq_ [Samburu]
saq_KE [Samburu (Kenya)]
sbp_ [Sangu]
sbp_TZ [Sangu (Tanzania)]
se_ [Northern Sami]
se_FI [Northern Sami (Finland)]
se_NO [Northern Sami (Norway)]
se_SE [Northern Sami (Sweden)]
seh_ [Sena]
seh_MZ [Sena (Mozambique)]
ses_ [Koyraboro Senni]
ses_ML [Koyraboro Senni (Mali)]
sg_ [Sango]
sg_CF [Sango (Central African Republic)]
shi_ [Tachelhit (Latin)]
shi_ [Tachelhit (Tifinagh)]
shi_ [Tachelhit]
shi_MA [Tachelhit (Latin,Morocco)]
shi_MA [Tachelhit (Tifinagh,Morocco)]
si_ [Sinhala]
si_LK [Sinhala (Sri Lanka)]
sk_ [Slovak]
sk_SK [Slovak (Slovakia)]
sl_ [Slovenian]
sl_SI [Slovenian (Slovenia)]
smn_ [Inari Sami]
smn_FI [Inari Sami (Finland)]
sn_ [Shona]
sn_ZW [Shona (Zimbabwe)]
so_ [Somali]
so_DJ [Somali (Djibouti)]
so_ET [Somali (Ethiopia)]
so_KE [Somali (Kenya)]
so_SO [Somali (Somalia)]
sq_ [Albanian]
sq_AL [Albanian (Albania)]
sq_MK [Albanian (Macedonia (FYROM))]
sq_XK [Albanian (Kosovo)]
sr_ [Serbian (Cyrillic)]
sr_ [Serbian (Latin)]
sr_ [Serbian]
sr_BA [Serbian (Cyrillic,Bosnia & Herzegovina)]
sr_BA [Serbian (Latin,Bosnia & Herzegovina)]
sr_ME [Serbian (Cyrillic,Montenegro)]
sr_ME [Serbian (Latin,Montenegro)]
sr_RS [Serbian (Cyrillic,Serbia)]
sr_RS [Serbian (Latin,Serbia)]
sr_XK [Serbian (Cyrillic,Kosovo)]
sr_XK [Serbian (Latin,Kosovo)]
sv_ [Swedish]
sv_AX [Swedish (Åland Islands)]
sv_FI [Swedish (Finland)]
sv_SE [Swedish (Sweden)]
sw_ [Swahili]
sw_CD [Swahili (Congo (DRC))]
sw_KE [Swahili (Kenya)]
sw_TZ [Swahili (Tanzania)]
sw_UG [Swahili (Uganda)]
ta_ [Tamil]
ta_IN [Tamil (India)]
ta_LK [Tamil (Sri Lanka)]
ta_MY [Tamil (Malaysia)]
ta_SG [Tamil (Singapore)]
te_ [Telugu]
te_IN [Telugu (India)]
teo_ [Teso]
teo_KE [Teso (Kenya)]
teo_UG [Teso (Uganda)]
th_ [Thai]
th_TH [Thai (Thailand)]
ti_ [Tigrinya]
ti_ER [Tigrinya (Eritrea)]
ti_ET [Tigrinya (Ethiopia)]
to_ [Tongan]
to_TO [Tongan (Tonga)]
tr_ [Turkish]
tr_CY [Turkish (Cyprus)]
tr_TR [Turkish (Turkey)]
twq_ [Tasawaq]
twq_NE [Tasawaq (Niger)]
tzm_ [Central Atlas Tamazight]
tzm_MA [Central Atlas Tamazight (Morocco)]
ug_ [Uyghur]
ug_CN [Uyghur (China)]
uk_ [Ukrainian]
uk_UA [Ukrainian (Ukraine)]
ur_ [Urdu]
ur_IN [Urdu (India)]
ur_PK [Urdu (Pakistan)]
uz_ [Uzbek (Arabic)]
uz_ [Uzbek (Cyrillic)]
uz_ [Uzbek (Latin)]
uz_ [Uzbek]
uz_AF [Uzbek (Arabic,Afghanistan)]
uz_UZ [Uzbek (Cyrillic,Uzbekistan)]
uz_UZ [Uzbek (Latin,Uzbekistan)]
vai_ [Vai (Latin)]
vai_ [Vai (Vai)]
vai_ [Vai]
vai_LR [Vai (Latin,Liberia)]
vai_LR [Vai (Vai,Liberia)]
vi_ [Vietnamese]
vi_VN [Vietnamese (Vietnam)]
vun_ [Vunjo]
vun_TZ [Vunjo (Tanzania)]
wae_ [Walser]
wae_CH [Walser (Switzerland)]
xog_ [Soga]
xog_UG [Soga (Uganda)]
yav_ [Yangben]
yav_CM [Yangben (Cameroon)]
yo_ [Yoruba]
yo_BJ [Yoruba (Benin)]
yo_NG [Yoruba (Nigeria)]
zgh_ [Standard Moroccan Tamazight]
zgh_MA [Standard Moroccan Tamazight (Morocco)]
zh_ [Chinese (Simplified Han)]
zh_ [Chinese (Traditional Han)]
zh_ [Chinese]
zh_CN [Chinese (Simplified Han,China)]
zh_HK [Chinese (Simplified Han,Hong Kong)]
zh_HK [Chinese (Traditional Han,Hong Kong)]
zh_MO [Chinese (Simplified Han,Macau)]
zh_MO [Chinese (Traditional Han,Macau)]
zh_SG [Chinese (Simplified Han,Singapore)]
zh_TW [Chinese (Traditional Han,Taiwan)]
zu_ [Zulu]
zu_ZA [Zulu (South Africa)]
set time1=%time%
call timeout 10
set time2=%time%
echo. time1
echo. time2
echo.
pause
Use r.URL.Query()
when you appending to existing query, if you are building new set of params use the url.Values
struct like so
package main
import (
"fmt"
"log"
"net/http"
"net/url"
"os"
)
func main() {
req, err := http.NewRequest("GET","http://api.themoviedb.org/3/tv/popular", nil)
if err != nil {
log.Print(err)
os.Exit(1)
}
// if you appending to existing query this works fine
q := req.URL.Query()
q.Add("api_key", "key_from_environment_or_flag")
q.Add("another_thing", "foo & bar")
// or you can create new url.Values struct and encode that like so
q := url.Values{}
q.Add("api_key", "key_from_environment_or_flag")
q.Add("another_thing", "foo & bar")
req.URL.RawQuery = q.Encode()
fmt.Println(req.URL.String())
// Output:
// http://api.themoviedb.org/3/tv/popularanother_thing=foo+%26+bar&api_key=key_from_environment_or_flag
}
On the same theme as other answers, keeping it simple
Sub PrintArray(Data As Variant, Cl As Range)
Cl.Resize(UBound(Data, 1), UBound(Data, 2)) = Data
End Sub
Sub Test()
Dim MyArray() As Variant
ReDim MyArray(1 To 3, 1 To 3) ' make it flexible
' Fill array
' ...
PrintArray MyArray, ActiveWorkbook.Worksheets("Sheet1").[A1]
End Sub
completed = (id) => {
var details = {
'id': id,
};
var formBody = [];
for (var property in details) {
var encodedKey = encodeURIComponent(property);
var encodedValue = encodeURIComponent(details[property]);
formBody.push(encodedKey + "=" + encodedValue);
}
formBody = formBody.join("&");
fetch(markcompleted, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded'
},
body: formBody
})
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson, 'res JSON');
if (responseJson.status == "success") {
console.log(this.state);
alert("your todolist is completed!!");
}
})
.catch((error) => {
console.error(error);
});
};
Server side put this on top of .php:
header('Access-Control-Allow-Origin: *');
You can set specific domain restriction access:
header('Access-Control-Allow-Origin: https://www.example.com')
you have to put this in web.config :
<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="50000000" />
</webServices>
</scripting>
</system.web.extensions>
First add the new column to the old table through SSMStudio. Go to the database >> table >> columns. Right click on columns and choose new column. Follow the wizard. Then create the new table with the columns ordered as desired as follows:
select * into my_new_table from (
select old_col1, my_new_col, old_col2, old_col3
from my_old_table
) as A
;
Then rename the tables as desired through SSMStudio. Go to the database >> table >> choose rename.
Can you define further processing?
You can use a for loop to almost do this, but there's no easy way to insert CR/LF into an environment variable, so you'll have everything in one line. (you may be able to work around this depending on what you need to do.)
You're also limited to less than about 8k text files this way. (You can't create a single env var bigger than around 8k.)
Bill's suggestion of a for loop is probably what you need. You process the file one line at a time:
(use %i
at a command line %%i
in a batch file)
for /f "tokens=1 delims=" %%i in (file.txt) do echo %%i
more advanced:
for /f "tokens=1 delims=" %%i in (file.txt) do call :part2 %%i
goto :fin
:part2
echo %1
::do further processing here
goto :eof
:fin
SELECT a.* FROM orders a INNER JOIN (SELECT course,MAX(id) as id FROM orders WHERE admission_id=".$id." GROUP BY course ) AS b ON a.course = b.course AND a.id = b.id
With the Above Query you will get unique records with where condition
[Custom ListView with CheckBox]
If customlayout use checkbox, you must set checkbox focusable = false
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:id="@+id/rowTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:textSize="16sp" >
</TextView>
<CheckBox android:id="@+id/CheckBox01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:layout_alignParentRight="true"
android:layout_marginRight="6sp"
android:focusable="false"> // <---important
</CheckBox>
</RelativeLayout>
Readmore : A ListView with Checkboxes (Without Using ListActivity)
I was investigating this problem with regard to login-off via Azure Access Control Services, and wasn't able to connect head and tails of anything.
Then, stumbled over this post https://blogs.msdn.microsoft.com/ieinternals/2011/03/10/beware-cookie-sharing-in-cross-zone-scenarios/
In short, IE doesn't share cookies across zones (eg. Internet vs. Trusted sites).
So, if your IFrame target and html page are in different zone's P3P won't help with anything.
This is probably the simplest way of doing it:
sed -r 's/\s+//g' filename > output
mv ouput filename
I am new to the Android/Java world and was surprised to find out here (unless I don't understand what I read) that modal dialogs don't work. For some very obscure reasons for me at the moment, I got this "ShowMessage" equivalent with an ok button that works on my tablet in a very modal manner.
From my TDialogs.java module:
class DialogMes
{
AlertDialog alertDialog ;
private final Message NO_HANDLER = null;
public DialogMes(Activity parent,String aTitle, String mes)
{
alertDialog = new AlertDialog.Builder(parent).create();
alertDialog.setTitle(aTitle);
alertDialog.setMessage(mes) ;
alertDialog.setButton("OK",NO_HANDLER) ;
alertDialog.show() ;
}
}
Here's part of the test code:
public class TestDialogsActivity extends Activity implements DlgConfirmEvent
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btShowMessage = (Button) findViewById(R.id.btShowMessage);
btShowMessage.setOnClickListener(new View.OnClickListener() {
public void onClick(View view)
{
DialogMes dlgMes = new DialogMes( TestDialogsActivity.this,"Message","life is good") ;
}
});
I also implemented a modal Yes/No dialog following the interface approach suggested above by JohnnyBeGood, and it works pretty good too.
Correction:
My answer is not relevant to the question that I misunderstood. For some reason, I interpreted M. Romain Guy "you don't want to do that" as a no no to modal dialogs. I should have read: "you don't want to do that...this way".
I apologize.
Beside android.support.design.button.MaterialButton
(which mentioned by Gabriele Mariotti),
There is also another Button
widget called com.google.android.material.button.MaterialButton
which has different styles and extends from AppCompatButton
:
style="@style/Widget.MaterialComponents.Button"
style="@style/Widget.MaterialComponents.Button.UnelevatedButton"
style="@style/Widget.MaterialComponents.Button.TextButton"
style="@style/Widget.MaterialComponents.Button.Icon"
style="@style/Widget.MaterialComponents.Button.TextButton.Icon"
Filled, elevated Button
(default):
style="@style/Widget.MaterialComponents.Button"
style="@style/Widget.MaterialComponents.Button.UnelevatedButton"
style="@style/Widget.MaterialComponents.Button.TextButton"
style="@style/Widget.MaterialComponents.Button.Icon"
app:icon="@drawable/icon_24px" // Icons can be added from this
Read: https://material.io/develop/android/components/material-button/
A convenience class for creating a new Material button.
This class supplies updated Material styles for the button in the constructor. The widget will display the correct default Material styles without the use of the style flag.
function resize() {
var map_obj = document.getElementById("map_canvas");
/* map_obj.style.width = "500px";
map_obj.style.height = "225px";*/
if (map) {
map.checkResize();
map.panTo(new GLatLng(lat,lon));
}
}
<body onload="initialize()" onunload="GUnload()" onresize="resize()">
<div id="map_canvas" style="width: 100%; height: 100%">
</div>
One clean way to do this is to inject VirtualTime. It allows you to control time. First install VirtualTime
Install-Package VirtualTime
That allows to, for example, make time that moves 5 times faster on all calls to DateTime.Now or UtcNow
var DateTime = DateTime.Now.ToVirtualTime(5);
To make time move slower , eg 5 times slower do
var DateTime = DateTime.Now.ToVirtualTime(0.5);
To make time stand still do
var DateTime = DateTime.Now.ToVirtualTime(0);
Moving backwards in time is not tested yet
Here are a sample test:
[TestMethod]
public void it_should_make_time_move_faster()
{
int speedOfTimePerMs = 1000;
int timeToPassMs = 3000;
int expectedElapsedVirtualTime = speedOfTimePerMs * timeToPassMs;
DateTime whenTimeStarts = DateTime.Now;
ITime time = whenTimeStarts.ToVirtualTime(speedOfTimePerMs);
Thread.Sleep(timeToPassMs);
DateTime expectedTime = DateTime.Now.AddMilliseconds(expectedElapsedVirtualTime - timeToPassMs);
DateTime virtualTime = time.Now;
Assert.IsTrue(TestHelper.AreEqualWithinMarginOfError(expectedTime, virtualTime, MarginOfErrorMs));
}
You can check out more tests here:
What DateTime.Now.ToVirtualTime extension gives you is an instance of ITime which you pass to a method / class that depends on ITime. some DateTime.Now.ToVirtualTime is setup in the DI container of your choice
Here is another example injecting into a class contrustor
public class AlarmClock
{
private ITime DateTime;
public AlarmClock(ITime dateTime, int numberOfHours)
{
DateTime = dateTime;
SetTime = DateTime.UtcNow.AddHours(numberOfHours);
Task.Run(() =>
{
while (!IsAlarmOn)
{
IsAlarmOn = (SetTime - DateTime.UtcNow).TotalMilliseconds < 0;
}
});
}
public DateTime SetTime { get; set; }
public bool IsAlarmOn { get; set; }
}
[TestMethod]
public void it_can_be_injected_as_a_dependency()
{
//virtual time has to be 1000*3.75 faster to get to an hour
//in 1000 ms real time
var dateTime = DateTime.Now.ToVirtualTime(1000 * 3.75);
var numberOfHoursBeforeAlarmSounds = 1;
var alarmClock = new AlarmClock(dateTime, numberOfHoursBeforeAlarmSounds);
Assert.IsFalse(alarmClock.IsAlarmOn);
System.Threading.Thread.Sleep(1000);
Assert.IsTrue(alarmClock.IsAlarmOn);
}
Generally, I agree with @kgrittn's advice. Go for it.
But to address your basic question about concat()
: The new function concat()
is useful if you need to deal with null values - and null has neither been ruled out in your question nor in the one you refer to.
If you can rule out null values, the good old (SQL standard) concatenation operator ||
is still the best choice, and @luis' answer is just fine:
SELECT col_a || col_b;
If either of your columns can be null, the result would be null in that case. You could defend with COALESCE
:
SELECT COALESCE(col_a, '') || COALESCE(col_b, '');
But that get tedious quickly with more arguments. That's where concat()
comes in, which never returns null, not even if all arguments are null. Per documentation:
NULL arguments are ignored.
SELECT concat(col_a, col_b);
The remaining corner case for both alternatives is where all input columns are null in which case we still get an empty string ''
, but one might want null instead (at least I would). One possible way:
SELECT CASE
WHEN col_a IS NULL THEN col_b
WHEN col_b IS NULL THEN col_a
ELSE col_a || col_b
END;
This gets more complex with more columns quickly. Again, use concat()
but add a check for the special condition:
SELECT CASE WHEN (col_a, col_b) IS NULL THEN NULL
ELSE concat(col_a, col_b) END;
How does this work?
(col_a, col_b)
is shorthand notation for a row type expression ROW (col_a, col_b)
. And a row type is only null if all columns are null. Detailed explanation:
Also, use concat_ws()
to add separators between elements (ws
for "with separator").
An expression like the one in Kevin's answer:
SELECT $1.zipcode || ' - ' || $1.city || ', ' || $1.state;
is tedious to prepare for null values in PostgreSQL 8.3 (without concat()
). One way (of many):
SELECT COALESCE(
CASE
WHEN $1.zipcode IS NULL THEN $1.city
WHEN $1.city IS NULL THEN $1.zipcode
ELSE $1.zipcode || ' - ' || $1.city
END, '')
|| COALESCE(', ' || $1.state, '');
STABLE
concat()
and concat_ws()
are STABLE
functions, not IMMUTABLE
because they can invoke datatype output functions (like timestamptz_out
) that depend on locale settings.
Explanation by Tom Lane.
This prohibits their direct use in index expressions. If you know that the result is actually immutable in your case, you can work around this with an IMMUTABLE
function wrapper. Example here:
The easiest answer is given by W3schools. https://www.w3schools.com/html/html_youtube.asp
<iframe width="640" height="520"
src="https://www.youtube.com/embed/<VideoID>">
</iframe>
The C++ syntax is like this:
class Bar : public Foo {
// ...
void printStuff() {
Foo::printStuff(); // calls base class' function
}
};
According to @jaiswal Rajan in his answer. You can do a pushViewController like this:
let storyBoard: UIStoryboard = UIStoryboard(name: "NewBotStoryboard", bundle: nil)
let newViewController = storyBoard.instantiateViewController(withIdentifier: "NewViewController") as! NewViewController
self.navigationController?.pushViewController(newViewController, animated: true)
Calculate the Distance
D = Math.Sqrt(Math.Pow(center_x - x, 2) + Math.Pow(center_y - y, 2))
return D <= radius
that's in C#...convert for use in python...
For Unix
grep "ARCHITECTURE" $ORACLE_HOME/inventory/ContentsXML/oraclehomeproperties.xml
And the output is:
<PROPERTY NAME="ARCHITECTURE" VAL="64"/>
For Windows
findstr "ARCHITECTURE" %ORACLE_HOME%\inventory\ContentsXML\oraclehomeproperties.xml
And the output can be:
<PROPERTY NAME="ARCHITECTURE" VAL="64"/>
Summary
Microsoft Security Updates 896358 & 840315 block display of CHM file contents when opened from a network drive (or a UNC path). This is Windows' attempt to stop attack vectors for viruses/malware from infecting your computer and has blocked out the .chm file that draw data over the "InfoTech" protocol, which this chm file uses.
Microsoft's summary of the problem: http://support.microsoft.com/kb/896054
Solutions
If you are using Windows Server 2008, Windows 7, windows has created a quick fix. Right click the chm file, and you will get the "yourfile.chm Properties" dialog box, at the bottom, a button called "Unblock" appears. Click Unblock and press OK, and try to open the chm file again, it works correctly. This option is not available for earlier versions of Windows before WindowsXP (SP3).
Solve the problem by moving your chm file OFF the network drive. You may be unaware you are using a network drive, double check now: Right click your .chm file, click properties and look at the "location" field. If it starts with two backslashes like this: \\epicserver\blah\
, then you are using a networked drive. So to fix it, Copy the chm file, and paste it into a local drive, like C:\ or E:. Then try to reopen the chm file, windows does not freak out.
Last resort, if you can't copy/move the file off the networked drive. If you must open it where it sits, and you are using a lesser version of windows like XP, Vista, ME or other, you will have to manually tell Windows not to freak out over this .chm file. HHReg (HTML Help Registration Utility) Utility Automates this Task. Basically you download the HHReg utility, load your .chm file, press OK, and it will create the necessary registry keys to tell Windows not to block it. For more info: http://www.winhelponline.com/blog/fix-cannot-view-chm-files-network-xp-2003-vista/
Windows 8 or 10? --> Upgrade to Windows XP.