Assuming your example text is representative of all the text, one line would consume about 75 bytes on my machine:
In [3]: sys.getsizeof('usedfor zipper fasten_coat')
Out[3]: 75
Doing some rough math:
75 bytes * 8,000,000 lines / 1024 / 1024 = ~572 MB
So roughly 572 meg to store the strings alone for one of these files. Once you start adding in additional, similarly structured and sized files, you'll quickly approach your virtual address space limits, as mentioned in @ShadowRanger's answer.
If upgrading your python isn't feasible for you, or if it only kicks the can down the road (you have finite physical memory after all), you really have two options: write your results to temporary files in-between loading in and reading the input files, or write your results to a database. Since you need to further post-process the strings after aggregating them, writing to a database would be the superior approach.
How about getSelectedDate? Anyway, specifically on your code question, the problem is with this line:
new SimpleDateFormat("yyyy-MM-dd");
The string that goes in the constructor has to match the format of the date. The documentation for how to do that is here. Looks like you need something close to "EEE MMM d HH:mm:ss zzz yyyy"
I've faced this issue several times on MacOS. Git is case sensitive but Mac is only case preserving.
Someone commit a file: Foobar.java
and after a few days decides to rename it to FooBar.java
. When you pull the latest code it fails with The following untracked working tree files would be overwritten by checkout...
The only reliable way that I've seen that fixes this is:
git rm Foobar.java
git commit -m 'TEMP COMMIT!!'
git rebase --continue
git rebase -i HEAD~2
and drop
the TEMP COMMIT!!
FooBar.java
Using the Apache Commons IO library...
boolean isFileUnlocked = false;
try {
org.apache.commons.io.FileUtils.touch(yourFile);
isFileUnlocked = true;
} catch (IOException e) {
isFileUnlocked = false;
}
if(isFileUnlocked){
// Do stuff you need to do with a file that is NOT locked.
} else {
// Do stuff you need to do with a file that IS locked
}
Remove images which have none
as the repository name using the following:
docker rmi $(docker images | grep "^<none" | awk '{print $3}')
Remove images which have none
tag or repository name:
docker rmi $(docker images | grep "none" | awk '{print $3}')
Try to change Long
object type to long
primitive type (if using primitives is ok for you).
I had the same problem and changing type helped me.
One thing to check if the redis commands are not working for you is if your redis-server.pid is actually being created. You specify the location of where this file is in
/etc/systemd/system/redis.service
and it should have a section that looks something like this:
[Service]
Type=forking
User=redis
Group=redis
ExecStart=/usr/bin/redis-server /etc/redis/redis.conf
PIDFile=/run/redis/redis-server.pid
TimeoutStopSec=0
Restart=always
Check the location and permissions of the PIDFile directory (in my case, '/run/redis'). I was trying to restart the service logged in as deploy but the directory permissions were listed as
drwxrwsr-x 2 redis redis 40 Jul 20 17:37 redis
If you need a refresher on linux permissions, check this out. But the problem was I was executing the restart as my deploy user which the permissions above are r-x, not allowing my user to write to the PIDFile directory.
Once I realized that, I logged in using root, reran the restart command on the redis (service redis restart
) and everything worked. That was a headache but hopefully this saves someone a little time.
At the time the compiler encounters the call to swapCase in main(), it does not know about the function swapCase, so it reports an error. You can either move the definition of swapCase above main, or declare swap case above main:
void swapCase(char* name);
Also, the 32 in swapCase causes the reader to pause and wonder. The comment helps! In this context, it would add clarity to write
if ('A' <= name[i] && name[i] <= 'Z')
name[i] += 'a' - 'A';
else if ('a' <= name[i] && name[i] <= 'z')
name[i] += 'A' - 'a';
The construction in my if-tests is a matter of personal style. Yours were just fine. The main thing is the way to modify name[i] -- using the difference in 'a' vs. 'A' makes it more obvious what is going on, and nobody has to wonder if the '32' is actually correct.
Good luck learning!
No, it's simply a typo, the "list" at the end must be capitalized. You can nest loops over the same variable just fine (although there's rarely a good reason to).
However, there are other problems with the code. For starters, you're iterating through lists, so i
and j
will be items not indices. Furthermore, you can't change a collection while iterating over it (well, you "can" in that it runs, but madness lies that way - for instance, you'll propably skip over items). And then there's the complexity problem, your code is O(n^2). Either convert the list into a set
and back into a list
(simple, but shuffles the remaining list items) or do something like this:
seen = set()
new_x = []
for x in xs:
if x in seen:
continue
seen.add(x)
new_xs.append(x)
Both solutions require the items to be hashable. If that's not possible, you'll probably have to stick with your current approach sans the mentioned problems.
'raw string' means it is stored as it appears. For example, '\'
is just a backslash instead of an escaping.
If you added (or have) a CSS class or id to the parent element, then you can do something like this:
<div id="parent">
<div>
</div>
</div>
JavaScript:
document.getElementById("parent").onmouseout = function(e) {
e = e ? e : window.event //For IE
if(e.target.id == "parent") {
//Do your stuff
}
}
So stuff only gets executed when the event is on the parent div.
Its just better to create a routing component that would handle all your routes! From the angular website documentation! That's good practice!
ng generate module app-routing --flat --module=app
The above CLI generates a routing module and adds to your app module, all you need to do from the generated component is to declare your routes, also don't forget to add this:
exports: [
RouterModule
],
to your ng-module decorator as it doesn't come with the generated app-routing module by default!
I called SelectAll inside MouseUp event and it worked fine for me.
private bool _tailTextBoxFirstClick = false;
private void textBox1_MouseUp(object sender, MouseEventArgs e)
{
if(_textBoxFirstClick)
textBox1.SelectAll();
_textBoxFirstClick = false;
}
private void textBox1_Leave(object sender, EventArgs e)
{
_textBoxFirstClick = true;
textBox1.Select(0, 0);
}
string BaseWindow = driver.CurrentWindowHandle;
ReadOnlyCollection<string> handles = driver.WindowHandles;
foreach (string handle in handles)
{
if (handle != BaseWindow)
{
string title = driver.SwitchTo().Window(handle).Title;
Thread.Sleep(3000);
driver.SwitchTo().Window(handle).Title.Equals(title);
Thread.Sleep(3000);
}
}
Change
@RequestMapping(value = "/test", method = RequestMethod.POST)
To
@RequestMapping(value = "/test", method = RequestMethod.GET)
if you hit this, and don't really want to try and handle adding a day in code, then let the DB do it..
myDate >= '20090101 00:00:00' AND myDate < DATEADD(day,1,'20090101 00:00:00')
If you do include the time portion: make sure it references midnight. Otherwise you can simply omit the time:
myDate >= '20090101' AND myDate < DATEADD(day,1,'20090101')
and not worry about it.
You can use the ThenBy and ThenByDescending extension methods:
foobarList.OrderBy(x => x.Foo).ThenBy( x => x.Bar)
You need to change from queue import Queue
to from multiprocessing import Queue
.
The root reason is the former Queue is designed for threading module Queue while the latter is for multiprocessing.Process module.
For details, you can read some source code or contact me!
If we want partial match just like contains, we can chain the contain call like this :
def getSelectedTablesRows2(allTablesInfoDF: DataFrame, tableNames: Seq[String]): DataFrame = {
val tableFilters = tableNames.map(_.toLowerCase()).map(name => lower(col("table_name")).contains(name))
val finalFilter = tableFilters.fold(lit(false))((accu, newTableFilter) => accu or newTableFilter)
allTablesInfoDF.where(finalFilter)
}
For Windows users, Ruby doesn't set up .gemrc file. So you have to create .gemrc file in your home directory (echo %USERPROFILE%
) and put following line in it:
gem: --no-document
As already mentioned in previous answers, don't use --no-ri and --no-rdoc cause its deprecated. See it yourself:
gem help install
This is not a direct answer to the question, but in practice I often want to have an estimate of the number of rows that will be in the result set. For most type of queries, MySQL's "EXPLAIN" delivers that.
I for example use that to refuse to run a client query if the explain looks bad enough.
Then also daily run "ANALYZE LOCAL TABLE" (outside of replication, to prevent cluster locks) on your tables, on each involved MySQL server.
what about using CSS on UIWebView? something like
<style type="text/css">
<!—-
* {
-webkit-user-select: none;
}
-->
</style>
also you can read detail about block copy-paste using CSS http://rakaz.nl/2009/09/iphone-webapps-101-getting-safari-out-of-the-way.html
I had this same issue - I had just added the font-awesome cdn links - commenting out the bootstrap one below solved my issue.. didnt really troubleshoot it as the font awesome still worked -
<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.no-icons.min.css" rel="stylesheet">
All other answers don't quite solve the issue. They print the date formatted as mm/dd/yyyy but the question was regarding MM/dd/yyyy. Notice the subtle difference? MM indicates that a leading zero must pad the month if the month is a single digit, thus having it always be a double digit number.
i.e. whereas mm/dd would be 3/31, MM/dd would be 03/31.
I've created a simple function to achieve this. Notice that the same padding is applied not only to the month but also to the day of the month, which in fact makes this MM/DD/yyyy:
function getFormattedDate(date) {_x000D_
var year = date.getFullYear();_x000D_
_x000D_
var month = (1 + date.getMonth()).toString();_x000D_
month = month.length > 1 ? month : '0' + month;_x000D_
_x000D_
var day = date.getDate().toString();_x000D_
day = day.length > 1 ? day : '0' + day;_x000D_
_x000D_
return month + '/' + day + '/' + year;_x000D_
}
_x000D_
Update for ES2017 using String.padStart(), supported by all major browsers except IE.
function getFormattedDate(date) {_x000D_
let year = date.getFullYear();_x000D_
let month = (1 + date.getMonth()).toString().padStart(2, '0');_x000D_
let day = date.getDate().toString().padStart(2, '0');_x000D_
_x000D_
return month + '/' + day + '/' + year;_x000D_
}
_x000D_
In my case I needed to install "JST Server Adapters". I am running Eclipse 3.6 Helios RCP Edition.
Here are the steps I followed:
After that I could define new Server Runtime Environments.
EDIT: With Eclipse 3.7 Indigo Classic, Eclipse Kepler and Luna, the steps are the same (with appropriate update site) but you need both JST Server Adapters and JST Server Adapters Extentions to get the Server Runtime Environment options.
Here is a simple video recording example using the MediaRecorder:
public class VideoCapture extends Activity implements OnClickListener, SurfaceHolder.Callback {
MediaRecorder recorder;
SurfaceHolder holder;
boolean recording = false;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
recorder = new MediaRecorder();
initRecorder();
setContentView(R.layout.main);
SurfaceView cameraView = (SurfaceView) findViewById(R.id.CameraView);
holder = cameraView.getHolder();
holder.addCallback(this);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
cameraView.setClickable(true);
cameraView.setOnClickListener(this);
}
private void initRecorder() {
recorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
recorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT);
CamcorderProfile cpHigh = CamcorderProfile
.get(CamcorderProfile.QUALITY_HIGH);
recorder.setProfile(cpHigh);
recorder.setOutputFile("/sdcard/videocapture_example.mp4");
recorder.setMaxDuration(50000); // 50 seconds
recorder.setMaxFileSize(5000000); // Approximately 5 megabytes
}
private void prepareRecorder() {
recorder.setPreviewDisplay(holder.getSurface());
try {
recorder.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
finish();
} catch (IOException e) {
e.printStackTrace();
finish();
}
}
public void onClick(View v) {
if (recording) {
recorder.stop();
recording = false;
// Let's initRecorder so we can record again
initRecorder();
prepareRecorder();
} else {
recording = true;
recorder.start();
}
}
public void surfaceCreated(SurfaceHolder holder) {
prepareRecorder();
}
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
}
public void surfaceDestroyed(SurfaceHolder holder) {
if (recording) {
recorder.stop();
recording = false;
}
recorder.release();
finish();
}
}
It's from my book: Pro Android Media: Developing Graphics, Music, Video, and Rich Media Apps for Smartphones and Tablets
Also, do not forget to include these permissions in manifest:
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Simple answer is :
$('#first').select2().val()
and you can write by this way also:
$('#first').val()
i fixed this by modifying php.ini
file at C:\wamp\bin\apache\apache2.4.9\bin\
curl.cainfo = "C:/wamp/bin/php/php5.5.12/cacert.pem"
first i was trying by modifying php.ini
file at C:\wamp\bin\php\php5.5.12\
and it didn't work.
hope this helps someone who is searching for the right php.ini
to modify
Here is another one liner:
[[ -d /tmp/test ]] && rm -r /tmp/test
Add this code to manifest:
<application android:supportsRtl="true">
and then write this code on Oncreate:
getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
It works for me. ;)
I used:
git reset --hard
I lost some changes, but this is ok.
You shouldn't change the npm registry using .bat
files.
Instead try to use modify the .npmrc
file which is the configuration for npm
.
The correct command for changing registry is
npm config set registry <registry url>
you can find more information with npm help config
command, also check for privileges when and if you are running .bat
files this way.
After validation and before INSERT check if username already exists, using mysqli(procedural). This works:
//check if username already exists
include 'phpscript/connect.php'; //connect to your database
$sql = "SELECT username FROM users WHERE username = '$username'";
$result = $conn->query($sql);
if($result->num_rows > 0) {
$usernameErr = "username already taken"; //takes'em back to form
} else { // go on to INSERT new record
this will also work, if you like
xcopy C:\Test\Log "c:\Test\Backup-%date:~4,2%-%date:~7,2%-%date:~10,4%_%time:~0,2%%time:~3,2%" /s /i
del C:\Test\Log
You can get and set environment variables via os.environ
:
import os
user_home = os.environ["HOME"]
os.environ["PYTHONPATH"] = "..."
But since your interpreter is already running, this will have no effect. You're better off using
import sys
sys.path.append("...")
which is the array that your PYTHONPATH
will be transformed into on interpreter startup.
Use Enumerable.Contains function:
var result =
!(compareString.Contains(firstString) || compareString.Contains(secondString));
I had the same issue and already tried all of solutions but to no avail.
It turned out that using Java 9 was the problem. Installing a lower version Java (jdk 1.8.0_162) worked for me.
I do it like this, but perhaps it's only ASP.NET MVC 4
@ViewContext.RouteData.Values["controller"]
I set an environment variable to the value in the numeric format desired by doing this:
FOR /F "tokens=1,2,3,4 delims=/ " %a IN ('echo %date%') DO set DateRun=%d-%b-%c
Try to explain this question in a level referring to a little bit technology
Take MongoDB and Traditional SQL for comparison, imagine the scenario of posting a Tweet on Twitter. This tweet contains 9 pictures. How do you store this tweet and its corresponding pictures?
In terms of traditional relationship SQL, you can store the tweets and pictures in separate tables, and represent the connection through building a new table.
What's more, you can set a field which is an image type, and zip the 9 pictures into a binary document and store it in this field.
Using MongoDB, you could build a document like this (similar to the concept of a table in relational SQL):
{
"id":"XXX",
"user":"XXX",
"date":"xxxx-xx-xx",
"content":{
"text":"XXXX",
"picture":["p1.png","p2.png","p3.png"]
}
Therefore, in my opinion, the main difference is about how do you store the data and the storage level of the relationships between them.
In this example, the data is the tweet and the pictures. The different mechanism about storage level of relationship between them also play a important role in the difference between both.
I hope this small example helps show the difference between SQL and NoSQL (ACID and BASE).
Here's a link of picture about the goals of NoSQL from the Internet:
It should work as expected. Try to run the following example.
import pandas as pd
import io
data = """value
"2015-09-25 00:46" 71.925000
"2015-09-25 00:47" 71.625000
"2015-09-25 00:48" 71.333333
"2015-09-25 00:49" 64.571429
"2015-09-25 00:50" 72.285714"""
df = pd.read_table(io.StringIO(data), delim_whitespace=True)
# Converting the index as date
df.index = pd.to_datetime(df.index)
# Extracting hour & minute
df['A'] = df.index.hour
df['B'] = df.index.minute
df
# value A B
# 2015-09-25 00:46:00 71.925000 0 46
# 2015-09-25 00:47:00 71.625000 0 47
# 2015-09-25 00:48:00 71.333333 0 48
# 2015-09-25 00:49:00 64.571429 0 49
# 2015-09-25 00:50:00 72.285714 0 50
There are a couple of things you can't do with a primitive type:
null
valueObject
sUnless you need any of those, you should prefer primitive types, since they require less memory.
That is correct. When you do that you are casting it it into an employee
object, so that means you cannot access anything manager specific.
Downcasting is where you take a base class and then try and turn it into a more specific class. This can be accomplished with using is and an explicit cast like this:
if (employee is Manager)
{
Manager m = (Manager)employee;
//do something with it
}
or with the as
operator like this:
Manager m = (employee as Manager);
if (m != null)
{
//do something with it
}
If anything is unclear I'll be happy to correct it!
The user-contributed section in the manual page of rmdir
contains a decent implementation:
function rrmdir($dir) {
if (is_dir($dir)) {
$objects = scandir($dir);
foreach ($objects as $object) {
if ($object != "." && $object != "..") {
if (is_dir($dir. DIRECTORY_SEPARATOR .$object) && !is_link($dir."/".$object))
rrmdir($dir. DIRECTORY_SEPARATOR .$object);
else
unlink($dir. DIRECTORY_SEPARATOR .$object);
}
}
rmdir($dir);
}
}
SELECT PersonName, songName, status
FROM table
WHERE name IN ('Holly', 'Ryan')
If you are using parametrized Stored procedure:
INNER JOIN ON t.PersonName = newTable.PersonName
using a table variable which contains passed in namesYou can use this example and change it's implementation like this:
[self enumerateAttribute:NSParagraphStyleAttributeName
inRange:NSMakeRange(0, self.length)
options:0
usingBlock:^(id _Nullable value, NSRange range, BOOL * _Nonnull stop) {
NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
//add your specific settings for paragraph
//...
//...
[self removeAttribute:NSParagraphStyleAttributeName range:range];
[self addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:range];
}];
By design there isn't a built in mechanism for Windows to propagate an environment variable add/change/remove to an already running cmd.exe, either from another cmd.exe or from "My Computer -> Properties ->Advanced Settings -> Environment Variables".
If you modify or add a new environment variable outside of the scope of an existing open command prompt you either need to restart the command prompt, or, manually add using SET in the existing command prompt.
The latest accepted answer shows a partial work-around by manually refreshing all the environment variables in a script. The script handles the use case of changing environment variables globally in "My Computer...Environment Variables", but if an environment variable is changed in one cmd.exe the script will not propagate it to another running cmd.exe.
Add this code into the css file:
input {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
}
This will help.
What type of authentication do you use? Send the credentials using the properties Ben said before and setup a cookie handler. You already allow redirection, check your webserver if any redirection occurs (NTLM auth does for sure). If there is a redirection you need to store the session which is mostly stored in a session cookie.
I wanted to add this answer because I used the primary answer from this question as my basis for exporting from a datatable to Excel using OpenXML but then transitioned to OpenXMLWriter when I found it to be much faster than the above method.
You can find the full details in my answer in the link below. My code is in VB.NET though, so you'll have to convert it.
Using String.prototype.replace
with regex, as mentioned in the other answers, is certainly the best solution.
But, just for fun, you can also remove all whitespaces from a text by using String.prototype.split
and String.prototype.join
:
const text = ' a b c d e f g ';_x000D_
const newText = text.split(/\s/).join('');_x000D_
_x000D_
console.log(newText); // prints abcdefg
_x000D_
This is worked for me, Hope to help someone (Using my own button not FB login button )
CallbackManager callbackManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.activity_sign_in_user);
LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
@Override
public void onCompleted(JSONObject object, GraphResponse response) {
try {
Log.i("RESAULTS : ", object.getString("email"));
}catch (Exception e){
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "email");
request.setParameters(parameters);
request.executeAsync();
}
@Override
public void onCancel() {
}
@Override
public void onError(FacebookException error) {
Log.i("RESAULTS : ", error.getMessage());
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
callbackManager.onActivityResult(requestCode, resultCode, data);
super.onActivityResult(requestCode, resultCode, data);
}
boolean isEmailValid(CharSequence email) {
return android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
}
public void signupwith_facebook(View view) {
LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("public_profile","email"));
}
}
Use cl scr
on the Sql* command line tool to clear all the matter on the screen.
Will my existing implementations continue to work? If not, is there an easy to implement alternative.
The answer is yes, but not without a little work.
$.browser is an official plugin which was included in older versions of jQuery, so like any plugin you can simple copy it and incorporate it into your project or you can simply add it to the end of any jQuery release.
I have extracted the code for you incase you wish to use it.
// Limit scope pollution from any deprecated API
(function() {
var matched, browser;
// Use of jQuery.browser is frowned upon.
// More details: http://api.jquery.com/jQuery.browser
// jQuery.uaMatch maintained for back-compat
jQuery.uaMatch = function( ua ) {
ua = ua.toLowerCase();
var match = /(chrome)[ \/]([\w.]+)/.exec( ua ) ||
/(webkit)[ \/]([\w.]+)/.exec( ua ) ||
/(opera)(?:.*version|)[ \/]([\w.]+)/.exec( ua ) ||
/(msie) ([\w.]+)/.exec( ua ) ||
ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( ua ) ||
[];
return {
browser: match[ 1 ] || "",
version: match[ 2 ] || "0"
};
};
matched = jQuery.uaMatch( navigator.userAgent );
browser = {};
if ( matched.browser ) {
browser[ matched.browser ] = true;
browser.version = matched.version;
}
// Chrome is Webkit, but Webkit is also Safari.
if ( browser.chrome ) {
browser.webkit = true;
} else if ( browser.webkit ) {
browser.safari = true;
}
jQuery.browser = browser;
jQuery.sub = function() {
function jQuerySub( selector, context ) {
return new jQuerySub.fn.init( selector, context );
}
jQuery.extend( true, jQuerySub, this );
jQuerySub.superclass = this;
jQuerySub.fn = jQuerySub.prototype = this();
jQuerySub.fn.constructor = jQuerySub;
jQuerySub.sub = this.sub;
jQuerySub.fn.init = function init( selector, context ) {
if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) {
context = jQuerySub( context );
}
return jQuery.fn.init.call( this, selector, context, rootjQuerySub );
};
jQuerySub.fn.init.prototype = jQuerySub.fn;
var rootjQuerySub = jQuerySub(document);
return jQuerySub;
};
})();
If you're asking why anyone would need a depreciated plugin, I have prepared the following answer.
First and foremost the answer is compatibility. Since jQuery is plugin based, some developers opted to use $.browser and with the latest releases of jQuery which doesn't include $.browser all those plugins where rendered useless.
jQuery did release a migration plugin, which was created for developers to detect whether their plugin's used any depreciated dependencies such as $.browser.
Although this helped developers patch their plugin's. jQuery dropped $.browser completely so the above fix is probably the only solution until your developers patch or incorporate the above.
About: jQuery.browser
isValidJsonString - check for valid json string
JSON data types - string, number, object (JSON object), array, boolean, null (https://www.json.org/json-en.html)
falsy values in javascript - false, 0, -0, 0n, ", null, undefined, NaN - (https://developer.mozilla.org/en-US/docs/Glossary/Falsy)
JSON.parse
works well for number , boolean, null and valid json String won't raise any error. please refer example below
break when you parse undefined , object, array etc
function isValidJsonString(jsonString){
if(!(jsonString && typeof jsonString === "string")){
return false;
}
try{
JSON.parse(jsonString);
return true;
}catch(error){
return false;
}
}
I used:
TableLayout tablelayout = (TableLayout) view.findViewById(R.id.table);
tablelayout.setColumnShrinkable(1,true);
it worked for me. 1 is the number of column.
Make sure that there are more ?
than there are characters in the longest name:
ren *.txt "???????????????????????????? 1.1.txt"
See How does the Windows RENAME command interpret wildcards? for more info.
New Solution - 2014/12/01
For those who like regular expressions, there is JREN.BAT - a hybrid JScript/batch command line utility that will run on any version of Windows from XP forward.
jren "^.*(?=\.)" "$& 1.1" /fm "*.txt"
or
jren "^(.*)(\.txt)$" "$1 1.1$2" /i
Another clever way from that ancient thread:
int age = (
Int32.Parse(DateTime.Today.ToString("yyyyMMdd")) -
Int32.Parse(birthday.ToString("yyyyMMdd"))) / 10000;
You can use justify-content: space-between
in .test
like so:
.test {_x000D_
display: flex;_x000D_
justify-content: space-between;_x000D_
width: 20rem;_x000D_
border: .1rem red solid;_x000D_
}
_x000D_
<div class="test">_x000D_
<button>test</button>_x000D_
<button>test</button>_x000D_
</div>
_x000D_
For those who want to use Bootstrap 4 can use justify-content-between
:
div {_x000D_
width: 20rem;_x000D_
border: .1rem red solid;_x000D_
}
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" />_x000D_
<div class="d-flex justify-content-between">_x000D_
<button>test</button>_x000D_
<button>test</button>_x000D_
</div>
_x000D_
I remember it this way:
IEnumerable has one method GetEnumerator() which allows one to read through the values in a collection but not write to it. Most of the complexity of using the enumerator is taken care of for us by the for each statement in C#. IEnumerable has one property: Current, which returns the current element.
ICollection implements IEnumerable and adds few additional properties the most use of which is Count. The generic version of ICollection implements the Add() and Remove() methods.
IList implements both IEnumerable and ICollection, and add the integer indexing access to items (which is not usually required, as ordering is done in database).
The for
-in
loops for each property in an object or array. You can use this property to get to the value as well as change it.
Note: Private properties are not available for inspection, unless you use a "spy"; basically, you override the object and write some code which does a for-in loop inside the object's context.
For in looks like:
for (var property in object) loop();
Some sample code:
function xinspect(o,i){
if(typeof i=='undefined')i='';
if(i.length>50)return '[MAX ITERATIONS]';
var r=[];
for(var p in o){
var t=typeof o[p];
r.push(i+'"'+p+'" ('+t+') => '+(t=='object' ? 'object:'+xinspect(o[p],i+' ') : o[p]+''));
}
return r.join(i+'\n');
}
// example of use:
alert(xinspect(document));
Edit: Some time ago, I wrote my own inspector, if you're interested, I'm happy to share.
Edit 2: Well, I wrote one up anyway.
Maybe you are able to put the lf into the text, but it doesn't display? Make sure you have enough height for the control. For example:
Correct:
android:layout_height="wrap_content"
May be wrong:
android:layout_height="10dp"
Number("2,299.00".split(',').join('')); // 2299
The split function splits the string into an array using "," as a separator and returns an array.
The join function joins the elements of the array returned from the split function.
The Number() function converts the joined string to a number.
Most of the answers provided here address the number of incoming requests to your backend webservice, not the number of outgoing requests you can make from your ASP.net application to your backend service.
It's not your backend webservice that is throttling your request rate here, it is the number of open connections your calling application is willing to establish to the same endpoint (same URL).
You can remove this limitation by adding the following configuration section to your machine.config file:
<configuration>
<system.net>
<connectionManagement>
<add address="*" maxconnection="65535"/>
</connectionManagement>
</system.net>
</configuration>
You could of course pick a more reasonable number if you'd like such as 50 or 100 concurrent connections. But the above will open it right up to max. You can also specify a specific address for the open limit rule above rather than the '*' which indicates all addresses.
MSDN Documentation for System.Net.connectionManagement
Another Great Resource for understanding ConnectManagement in .NET
Hope this solves your problem!
EDIT: Oops, I do see you have the connection management mentioned in your code above. I will leave my above info as it is relevant for future enquirers with the same problem. However, please note there are currently 4 different machine.config files on most up to date servers!
There is .NET Framework v2 running under both 32-bit and 64-bit as well as .NET Framework v4 also running under both 32-bit and 64-bit. Depending on your chosen settings for your application pool you could be using any one of these 4 different machine.config files! Please check all 4 machine.config files typically located here:
You need to convert it to milliseconds by multiplying the timestamp by 1000:
java.util.Date dateTime=new java.util.Date((long)timeStamp*1000);
var element = document.getElementById('sample_id');
element.style.removeProperty("width");
element.style.removeProperty("height");
Add the below code
input[type="submit"]:hover {
border: 1px solid #999;
color: #000;
}
If you need only for these button then you can add id name
#paginate input[type="submit"]:hover {
border: 1px solid #999;
color: #000;
}
If you pasted your object into content.json
directly, it is invalid JSON. JSON keys and values must be wrapped in double quotes ("
not '
) unless the value is numeric, boolean, null
, or composite (array or object). JSON cannot contain functions or undefined
values. Below is your object as valid JSON.
{
"id": "whatever",
"name": "start",
"children": [
{
"id": "0.9685",
"name": " contents:queue"
},
{
"id": "0.79281",
"name": " contents:mqq_error"
}
]
}
You also had an extra }
.
If you are interested in portability between different SQL servers you should use ANSI SQL queries. String escaping in ANSI SQL is done by using double quotes ("). Unfortunately, this escaping method is not portable to MySQL, unless it is set in ANSI compatibility mode.
Personally, I always start my MySQL server with the --sql-mode='ANSI' argument since this allows for both methods for escaping. If you are writing queries that are going to be executed in a MySQL server that was not setup / is controlled by you, here is what you can do:
Enclose them in the following MySQL specific queries:
SET @OLD_SQL_MODE=@@SQL_MODE;
SET SESSION SQL_MODE='ANSI';
-- ANSI SQL queries
SET SESSION SQL_MODE=@OLD_SQL_MODE;
This way the only MySQL specific queries are at the beginning and the end of your .sql script. If you what to ship them for a different server just remove these 3 queries and you're all set. Even more conveniently you could create a script named: script_mysql.sql that would contain the above mode setting queries, source a script_ansi.sql script and reset the mode.
function deleteItem(this) {
if (confirm("Are you sure?")) {
$(this).remove();
}
return false;
}
You can also use jquery modalin same way
JQuery version
Are you sure? $(document).ready(function() {
$("#dialog-box").dialog({
autoOpen: false,
modal: true
});
$(".close").click(function(e) {
var currentElem = $(this);
$("#dialog-box").dialog({
buttons : {
"Confirm" : function() {
currentElem.remove()
},
"Cancel" : function() {
$(this).dialog("close");
}
}
});
$("#dialog-box").dialog("open");
});
});
There is no standard assert
in JavaScript itself. Perhaps you're using some library that provides one; for instance, if you're using Node.js, perhaps you're using the assertion module. (Browsers and other environments that offer a console implementing the Console API provide console.assert
.)
The usual meaning of an assert
function is to throw an error if the expression passed into the function is false; this is part of the general concept of assertion checking. Usually assertions (as they're called) are used only in "testing" or "debug" builds and stripped out of production code.
Suppose you had a function that was supposed to always accept a string. You'd want to know if someone called that function with something that wasn't a string (without having a type checking layer like TypeScript or Flow). So you might do:
assert(typeof argumentName === "string");
...where assert
would throw an error if the condition were false.
A very simple version would look like this:
function assert(condition, message) {
if (!condition) {
throw message || "Assertion failed";
}
}
Better yet, make use of the Error
object, which has the advantage of collecting a stack trace and such:
function assert(condition, message) {
if (!condition) {
throw new Error(message || "Assertion failed");
}
}
Works perfect for me:
(SELECT content FROM tblopportunitycomments WHERE opportunityid = 1 ORDER BY dateadded DESC LIMIT 1);
We can try a simpler one as follows:
docker image inspect image_id
This worked in Docker version:
DockerVersion": "18.05.0-ce"
You can also try this:
>>> list=[20, 20, 19, 4, 3, 2, 1,100,200,100]
>>> sorted(set(list), key=int, reverse=True)[1]
100
I've wrote such a simple class:
public static class WatermarkExtension
{
public static MvcHtmlString WatermarkFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression)
{
var watermark = ModelMetadata.FromLambdaExpression(expression, html.ViewData).Watermark;
var htmlEncoded = HttpUtility.HtmlEncode(watermark);
return new MvcHtmlString(htmlEncoded);
}
}
The usage as such:
@Html.TextBoxFor(model => model.AddressSuffix, new {placeholder = Html.WatermarkFor(model => model.AddressSuffix)})
And property in a viewmodel:
[Display(ResourceType = typeof (Resources), Name = "AddressSuffixLabel", Prompt = "AddressSuffixPlaceholder")]
public string AddressSuffix
{
get { return _album.AddressSuffix; }
set { _album.AddressSuffix = value; }
}
Notice Prompt parameter. In this case I use strings from resources for localization but you can use just strings, just avoid ResourceType parameter.
To work in objective-c I have to put the following lines in viewWillAppear
in my CustomViewController.
[self.navigationController.navigationBar setBarTintColor:[UIColor whiteColor]];
[self.navigationController.navigationBar setTranslucent:NO];
For Swift2.x this works:
self.navigationController?.navigationBar.barTintColor = UIColor.redColor()
For Swift3.x this works:
self.navigationController?.navigationBar.barTintColor = UIColor.red
I had this problem after closing docker will pulling a container docker pull mongo
. At first I was getting weird errors so I purged docker sudo apt-get purge docker.io
and reinstalled sudo apt-get install docker.io
... all of this did nothing. I couldn't even run the hello-world container. The correct fix for me at least was:
systemctl unmask docker.service
systemctl unmask docker.socket
systemctl start docker.service
After this I could pull mongo and run hello world.
Cheers!
I'd like to illustrate how the three terms are implemented in Rails. ActiveRecord calls any type of relationship between two models an association
. One would not find very often the terms composition
and aggregation
, when reading documentation or articles, related to ActiveRecord. An association is created by adding one of the association class macros to the body of the class. Some of these macros are belongs_to
, has_one
, has_many
etc..
If we want to set up a composition
or aggregation
, we need to add belongs_to
to the owned model (also called child) and has_one
or has_many
to the owning model (also called parent). Wether we set up composition
or aggregation
depends on the options we pass to the belongs_to
call in the child model. Prior to Rails 5, setting up belongs_to
without any options created an aggregation
, the child could exist without a parent. If we wanted a composition
, we needed to explicitly declare this by adding the option required: true
:
class Room < ActiveRecord::Base
belongs_to :house, required: true
end
In Rails 5 this was changed. Now, declaring a belongs_to
association creates a composition
by default, the child cannot exist without a parent. So the above example can be re-written as:
class Room < ApplicationRecord
belongs_to :house
end
If we want to allow the child object to exist without a parent, we need to declare this explicitly via the option optional
class Product < ApplicationRecord
belongs_to :category, optional: true
end
Use:
#!/bin/bash
s1="hi"
s2="hi"
if [ "x$s1" == "x$s2" ]
then
echo match
fi
Adding an additional string inside makes it more safe.
You could also use another notation for single-line commands:
[ "x$s1" == "x$s2" ] && echo match
JSON is a domain-specific language (DSL) and a data format independent of JavaScript, and as such has its own MIME type, application/json
. Respect for MIME types is of course client driven, so text/plain
may do for transfer of bytes, but then you would be pushing up interpretation to the vendor application domain unnecessarily - application/json
. Would you transfer XML via text/plain
?
But honestly, your choice of MIME type is advice to the client as to how to interpret the data- text/plain
or text/HTML
(when it's not HTML) is like type erasure- it's as uninformative as making all your objects of type Object in a typed language.
No browser runtime I know of will take a JSON document and automatically make it available to the runtime as a JavaScript accessible object without intervention, but if you are working with a crippled client, that's an entirely different matter. But that's not the whole story- RESTful JSON services often don't have JavaScript runtimes, but it doesn't stop them using JSON as a viable data interchange format. If clients are that crippled... then I would consider perhaps HTML injection via an Ajax templating service instead.
Application/JSON!
The accepted solution from Dallas was working for us if we use Load Balancer on the Citrix Netscaler (without WAF policy).
The download of the file doesn't work through the LB of the Netscaler when it is associated with WAF as the current scenario (Content-length not being correct) is a RFC violation and AppFW resets the connection, which doesn't happen when WAF policy is not associated.
So what was missing was:
Response.End();
See also: Trying to stream a PDF file with asp.net is producing a "damaged file"
As mentioned by nicholas.hauschild injecting Spring context is not a good idea. In your case, @Scope("request") is enough to fix it. But let say you need several instances of LoginAction
in controller method. In this case, I would recommend to create the bean of Supplier (Spring 4 solution):
@Bean
public Supplier<LoginAction> loginActionSupplier(LoginAction loginAction){
return () -> loginAction;
}
Then inject it into controller:
@Controller
public class HomeController {
@Autowired
private Supplier<LoginAction> loginActionSupplier;
As already mentioned its just a facade and it helps to switch between different logger implementation easily. For example if you want to use log4j implementation.
A sample code would looks like below.
If you use maven get the dependencies
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.6</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.5</version>
</dependency>
Have the below in log4j.properties in location src/main/resources/log4j.properties
log4j.rootLogger=DEBUG, STDOUT, file
log4j.appender.STDOUT=org.apache.log4j.ConsoleAppender
log4j.appender.STDOUT.layout=org.apache.log4j.PatternLayout
log4j.appender.STDOUT.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=mylogs.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{dd-MM-yyyy HH:mm:ss} %-5p %c{1}:%L - %m%n
Hello world code below would prints in console and to a log file as per above configuration.
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class HelloWorld {
public static void main(String[] args) {
Logger logger = LoggerFactory.getLogger(HelloWorld.class);
logger.info("Hello World");
}
}
If you are developing for iOS >10.2 with Swift 4 then you can try my solution. I mixed up this and this tutorial and came up with a ViewController which scans a QR Code and print()
it out. I also have a Switch in my UI to toggle the camera light, might be helpful as well. For now I only tested it on a iPhone SE, please let me know if it doesn't work on newer iPhones.
Here you go:
import UIKit
import AVFoundation
class QRCodeScanner: UIViewController, AVCaptureMetadataOutputObjectsDelegate {
let captureSession: AVCaptureSession = AVCaptureSession()
var videoPreviewLayer: AVCaptureVideoPreviewLayer?
let qrCodeFrameView: UIView = UIView()
var captureDevice: AVCaptureDevice?
override func viewDidLoad() {
// Get the back-facing camera for capturing videos
let deviceDiscoverySession = AVCaptureDevice.DiscoverySession(deviceTypes: [.builtInWideAngleCamera, .builtInDualCamera], mediaType: AVMediaType.video, position: .back)
captureDevice = deviceDiscoverySession.devices.first
if captureDevice == nil {
print("Failed to get the camera device")
return
}
do {
// Get an instance of the AVCaptureDeviceInput class using the previous device object.
let input = try AVCaptureDeviceInput(device: captureDevice!)
// Set the input device on the capture session.
captureSession.addInput(input)
// Initialize a AVCaptureMetadataOutput object and set it as the output device to the capture session.
let captureMetadataOutput = AVCaptureMetadataOutput()
captureSession.addOutput(captureMetadataOutput)
// Set delegate and use the default dispatch queue to execute the call back
captureMetadataOutput.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
captureMetadataOutput.metadataObjectTypes = [AVMetadataObject.ObjectType.qr]
// Initialize the video preview layer and add it as a sublayer to the viewPreview view's layer.
videoPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
if let videoPreviewLayer = videoPreviewLayer {
videoPreviewLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill
videoPreviewLayer.frame = view.layer.bounds
view.layer.addSublayer(videoPreviewLayer)
// Start video capture.
captureSession.startRunning()
if let hasFlash = captureDevice?.hasFlash, let hasTorch = captureDevice?.hasTorch {
if hasFlash && hasTorch {
view.bringSubview(toFront: bottomBar)
try captureDevice?.lockForConfiguration()
}
}
}
// QR Code Overlay
qrCodeFrameView.layer.borderColor = UIColor.green.cgColor
qrCodeFrameView.layer.borderWidth = 2
view.addSubview(qrCodeFrameView)
view.bringSubview(toFront: qrCodeFrameView)
} catch {
// If any error occurs, simply print it out and don't continue any more.
print("Error: \(error)")
return
}
}
// MARK: Buttons and Switch
@IBAction func switchFlashChanged(_ sender: UISwitch) {
do {
if sender.isOn {
captureDevice?.torchMode = .on
} else {
captureDevice?.torchMode = .off
}
}
}
// MARK: AVCaptureMetadataOutputObjectsDelegate
func metadataOutput(_ output: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection) {
// Check if the metadataObjects array is not nil and it contains at least one object.
if metadataObjects.count == 0 {
qrCodeFrameView.frame = CGRect.zero
return
}
// Get the metadata object.
let metadataObj = metadataObjects[0] as! AVMetadataMachineReadableCodeObject
if metadataObj.type == AVMetadataObject.ObjectType.qr {
// If the found metadata is equal to the QR code metadata then update the status label's text and set the bounds
let barCodeObject = videoPreviewLayer?.transformedMetadataObject(for: metadataObj)
qrCodeFrameView.frame = barCodeObject!.bounds
print("QR Code: \(metadataObj.stringValue)")
}
}
}
If you happen to be using date in a MacOS environment, try this:
ST1:~ ejf$ date
Mon Feb 20 21:55:48 CST 2017
ST1:~ ejf$ date -v-1m +%m
01
ST1:~ ejf$ date -v+1m +%m
03
Also, I'd rather calculate the previous and next month on the first day of each month, this way you won't have issues with months ending the 30/31 or 28/29 (Feb/Feb leap year)
Here's another way to force a type-cast even between incompatible types and interfaces where TS compiler normally complains:
export function forceCast<T>(input: any): T {
// ... do runtime checks here
// @ts-ignore <-- forces TS compiler to compile this as-is
return input;
}
Then you can use it to force cast objects to a certain type:
import { forceCast } from './forceCast';
const randomObject: any = {};
const typedObject = forceCast<IToDoDto>(randomObject);
Note that I left out the part you are supposed to do runtime checks before casting for the sake of reducing complexity. What I do in my project is compiling all my .d.ts
interface files into JSON schemas and using ajv
to validate in runtime.
You need to use get
to obtain the value rather than the character name of the object as returned by ls
:
x <- 1L
typeof(ls())
[1] "character"
typeof(get(ls()))
[1] "integer"
Alternatively, for the problem as presented you might want to use eapply
:
eapply(.GlobalEnv,typeof)
$x
[1] "integer"
$a
[1] "double"
$b
[1] "character"
$c
[1] "list"
You can't get a count of rows directly from a data reader because it's what is known as a firehose cursor - which means that the data is read on a row by row basis based on the read being performed. I'd advise against doing 2 reads on the data because there's the potential that the data has changed between doing the 2 reads, and thus you'd get different results.
What you could do is read the data into a temporary structure, and use that in place of the second read. Alternatively, you'll need to change the mechanism by which you retrieve the data and use something like a DataTable instead.
I am very thankful for @Logan's answer. It helps a lot to create a bridge file and setups.
But after doing all these steps I'm still not getting an Objective-C class in Swift.
I used the cocoapods
library and integrated it into my project. Which is pod "pop"
.
So if you are using Objective-C pods in Swift then there may be a chance that you can not able to get or import
the classes into Swift.
The simple thing you have to do is:
<YOUR-PROJECT>-Bridging-Header
file and#import <ObjC_Framework>
to @import ObjC_Framework
For example: (Pop library)
Replace
#import <pop/POP.h>
with
@import pop;
Use clang import
when #import
is not working.
@Neil's answer is one (perfectly valid!) way of doing it, but you can also simply call matplotlib.use('Agg')
before importing matplotlib.pyplot
, and then continue as normal.
E.g.
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(range(10))
fig.savefig('temp.png')
You don't have to use the Agg backend, as well. The pdf, ps, svg, agg, cairo, and gdk backends can all be used without an X-server. However, only the Agg backend will be built by default (I think?), so there's a good chance that the other backends may not be enabled on your particular install.
Alternately, you can just set the backend parameter in your .matplotlibrc
file to automatically have matplotlib.pyplot
use the given renderer.
You may try this :
string s = "";
foreach(DataRowView drv in checkedListBox1.CheckedItems)
{
s += drv[0].ToString()+",";
}
s=s.TrimEnd(',');
Actually, I found a somewhat quirky way to do this. Add the protocol to your web.config, but inside a location element. Specify the webservice location as the path attribute, like so:
<location path="YourWebservice.asmx">
<system.web>
<webServices>
<protocols>
<add name="HttpGet"/>
<add name="HttpPost"/>
</protocols>
</webServices>
</system.web>
</location>
Make sure that both projects have same target framework version here: right click on project -> properties -> application (tab) -> target framework
Also, make sure that the project "logger" (which you want to include in the main project) has the output type "Class Library" in: right click on project -> properties -> application (tab) -> output type
Finally, Rebuild the solution.
That's correct, your response is an object with fields:
{
"page": 1,
"results": [ ... ]
}
So you in fact want to iterate the results
field only:
this.data = res.json()['results'];
... or even easier:
this.data = res.json().results;
Set @TableName to the name of your table.
declare @TableName sysname = 'TableName'
declare @Result varchar(max) = 'public class ' + @TableName + '
{'
select @Result = @Result + '
public ' + ColumnType + NullableSign + ' ' + ColumnName + ' { get; set; }
'
from
(
select
replace(col.name, ' ', '_') ColumnName,
column_id ColumnId,
case typ.name
when 'bigint' then 'long'
when 'binary' then 'byte[]'
when 'bit' then 'bool'
when 'char' then 'string'
when 'date' then 'DateTime'
when 'datetime' then 'DateTime'
when 'datetime2' then 'DateTime'
when 'datetimeoffset' then 'DateTimeOffset'
when 'decimal' then 'decimal'
when 'float' then 'double'
when 'image' then 'byte[]'
when 'int' then 'int'
when 'money' then 'decimal'
when 'nchar' then 'string'
when 'ntext' then 'string'
when 'numeric' then 'decimal'
when 'nvarchar' then 'string'
when 'real' then 'float'
when 'smalldatetime' then 'DateTime'
when 'smallint' then 'short'
when 'smallmoney' then 'decimal'
when 'text' then 'string'
when 'time' then 'TimeSpan'
when 'timestamp' then 'long'
when 'tinyint' then 'byte'
when 'uniqueidentifier' then 'Guid'
when 'varbinary' then 'byte[]'
when 'varchar' then 'string'
else 'UNKNOWN_' + typ.name
end ColumnType,
case
when col.is_nullable = 1 and typ.name in ('bigint', 'bit', 'date', 'datetime', 'datetime2', 'datetimeoffset', 'decimal', 'float', 'int', 'money', 'numeric', 'real', 'smalldatetime', 'smallint', 'smallmoney', 'time', 'tinyint', 'uniqueidentifier')
then '?'
else ''
end NullableSign
from sys.columns col
join sys.types typ on
col.system_type_id = typ.system_type_id AND col.user_type_id = typ.user_type_id
where object_id = object_id(@TableName)
) t
order by ColumnId
set @Result = @Result + '
}'
print @Result
I know that you can modify a javascript file when using Google Chrome.
Warning: If you refresh the page, all changes will go back to original file. I recommend to copy/paste the code somewhere else if you want to use it again.
Hope this helps!
You can directly use curl to upgrade node to the latest version. Run the following command:
curl "https://nodejs.org/dist/latest/node-${VERSION:-$(wget -qO- https://nodejs.org/dist/latest/ | sed -nE 's|.*>node-(.*)\.pkg</a>.*|\1|p')}.pkg" > "$HOME/Downloads/node-latest.pkg" && sudo installer -store -pkg "$HOME/Downloads/node-latest.pkg" -target "/"
Reference: https://nodejs.org/en/download/package-manager/#macos
no problem doing it with asp.... it's most natural to do so with MVC, but can be done with standard asp as well.
The MVC framework has all sorts of helper classes for JSON, if you can, I'd suggest sussing in some MVC-love, if not, you can probably easily just get the JSON helper classes used by MVC in and use them in the context of asp.net.
edit:
here's an example of how to return JSON data with MVC. This would be in your controller class. This is out of the box functionality with MVC--when you crate a new MVC project this stuff gets auto-created so it's nothing special. The only thing that I"m doing is returning an actionResult that is JSON. The JSON method I'm calling is a method on the Controller class. This is all very basic, default MVC stuff:
public ActionResult GetData()
{
var data = new { Name="kevin", Age=40 };
return Json(data, JsonRequestBehavior.AllowGet);
}
This return data could be called via JQuery as an ajax call thusly:
$.get("/Reader/GetData/", function(data) { someJavacriptMethodOnData(data); });
This can be done through the youtube player API:
Working example:
<div id="player"></div>
<script src="http://www.youtube.com/player_api"></script>
<script>
// create youtube player
var player;
function onYouTubePlayerAPIReady() {
player = new YT.Player('player', {
width: '640',
height: '390',
videoId: '0Bmhjf0rKe8',
events: {
onReady: onPlayerReady,
onStateChange: onPlayerStateChange
}
});
}
// autoplay video
function onPlayerReady(event) {
event.target.playVideo();
}
// when video ends
function onPlayerStateChange(event) {
if(event.data === 0) {
alert('done');
}
}
</script>
One more JAVA 8 way:
LocalDateTime localDateTime = LocalDateTime.now().truncatedTo(ChronoUnit.HOURS);
But it's a lot more useful to edit the date that already exists.
12 to 24 hour time conversion and can be reversed if change time formate in output and input SimpleDateFormat class parameter
Test Data Input:
String input = "07:05:45PM"; timeCoversion12to24(input);
output
19:05:45
public static String timeCoversion12to24(String twelveHoursTime) throws ParseException {
//Date/time pattern of input date (12 Hours format - hh used for 12 hours)
DateFormat df = new SimpleDateFormat("hh:mm:ssaa");
//Date/time pattern of desired output date (24 Hours format HH - Used for 24 hours)
DateFormat outputformat = new SimpleDateFormat("HH:mm:ss");
Date date = null;
String output = null;
//Returns Date object
date = df.parse(twelveHoursTime);
//old date format to new date format
output = outputformat.format(date);
System.out.println(output);
return output;
}
You can write yourself a little console app and use System.Environment.Version to find out the version. Scott Hanselman gives a blog post about it.
Or look in the registry for the installed versions. HKLM\Software\Microsoft\NETFramework Setup\NDP
The backgroundTint
attribute will help you to add a tint(shade) to the background. You can provide a color value for the same in the form of - "#rgb", "#argb", "#rrggbb", or "#aarrggbb".
The backgroundTintMode
on the other hand will help you to apply the background tint. It must have constant values like src_over, src_in, src_atop,
etc.
Refer this to get a clear idea of the the constant values that can be used. Search for the backgroundTint
attribute and the description along with various attributes will be available.
The syntax to store the command output into a variable is var=$(command)
.
So you can directly do:
result=$(ls -l | grep -c "rahul.*patle")
And the variable $result
will contain the number of matches.
add $row = mysql_fetch_object($result);
after your mysql_query();
your html <img src="<?php echo $row->dvdimage; ?>" width="175" height="200" />
if your world is 100% ascii/utf-8
(a lot of use cases fit in that box):
b = bytearray(s, 'utf-8')
# process - e.g., lowercasing:
# b[0] = b[i+1] - 32
s = str(b, 'utf-8')
python 3.7.3
You should do it in componentDidMount
and refs callback
instead. Something like this
componentDidMount(){
this.nameInput.focus();
}
class App extends React.Component{_x000D_
componentDidMount(){_x000D_
this.nameInput.focus();_x000D_
}_x000D_
render() {_x000D_
return(_x000D_
<div>_x000D_
<input _x000D_
defaultValue="Won't focus" _x000D_
/>_x000D_
<input _x000D_
ref={(input) => { this.nameInput = input; }} _x000D_
defaultValue="will focus"_x000D_
/>_x000D_
</div>_x000D_
);_x000D_
}_x000D_
}_x000D_
_x000D_
ReactDOM.render(<App />, document.getElementById('app'));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.1/react.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.1/react-dom.js"></script>_x000D_
<div id="app"></div>
_x000D_
I would prefer generally foreach
when I don't need making arithmetic operations with their indices.
for (int[] x : array)
{
for (int y : x)
{
System.out.print(y + " ");
}
System.out.println();
}
You can use jQuery UI and do something like this
Html:
<button id="callConfirm">Confirm!</button>
<div id="dialog" title="Confirmation Required">
Are you sure about this?
</div>?
Javascript:
$("#dialog").dialog({
autoOpen: false,
modal: true,
buttons : {
"Confirm" : function() {
alert("You have confirmed!");
},
"Cancel" : function() {
$(this).dialog("close");
}
}
});
$("#callConfirm").on("click", function(e) {
e.preventDefault();
$("#dialog").dialog("open");
});
?
public boolean isTableExists(String tableName) {
boolean isExist = false;
Cursor cursor = db.rawQuery("select DISTINCT tbl_name from sqlite_master where tbl_name = '" + tableName + "'", null);
if (cursor != null) {
if (cursor.getCount() > 0) {
isExist = true;
}
cursor.close();
}
return isExist;
}
The query can be written slightly simpler, like this:
DECLARE @T INT = 2
SELECT CASE
WHEN @T < 1 THEN 'less than one'
WHEN @T = 1 THEN 'one'
ELSE 'greater than one'
END T
I got this error with my own code. My problem was that I had duplicate keys in the config file.
if you are using webstorm just make sure your default port is not 3000 from file -> settings -> Build, Execution, Deployment -> Debugger And there change
Built-in server port
and set it to "63342" or see this answer Change WebStorm LiveEdit Port (63342)
Table variables are just like int or varchar variables.
You don't need to drop them. They have the same scope rules as int or varchar variables
The scope of a variable is the range of Transact-SQL statements that can reference the variable. The scope of a variable lasts from the point it is declared until the end of the batch or stored procedure in which it is declared.
I know this is old post but JsonConvert actually has a different method so it would be
var product = new { Name = "", Price = 0 };
var jsonResponse = JsonConvert.DeserializeAnonymousType(json, product);
The solution consists in a regex pattern matching open and closing parenthesis
String str = "Your(String)";
// parameter inside split method is the pattern that matches opened and closed parenthesis,
// that means all characters inside "[ ]" escaping parenthesis with "\\" -> "[\\(\\)]"
String[] parts = str.split("[\\(\\)]");
for (String part : parts) {
// I print first "Your", in the second round trip "String"
System.out.println(part);
}
Writing in Java 8's style, this can be solved in this way:
Arrays.asList("Your(String)".split("[\\(\\)]"))
.forEach(System.out::println);
I hope it is clear.
I just found this on the Internet. This should work:
DWORD random = ((min) + rand()/(RAND_MAX + 1.0) * ((max) - (min) + 1));
new[,2]
is a factor, not a numeric vector. Transform it first
new$MY_NEW_COLUMN <-as.numeric(as.character(new[,2])) * 5
You can use .change
for what you want
$("input[@name='lom']").change(function(){
// Do something interesting here
});
as of jQuery 1.3
you no longer need the '@'. Correct way to select is:
$("input[name='lom']")
If what you're looking for is simply to blur the image edges you can simply use the box-shadow with an inset.
Working example: http://jsfiddle.net/d9Q5H/1/
HTML:
<div class="image-blurred-edge"></div>
CSS
.image-blurred-edge {
background-image: url('http://lorempixel.com/200/200/city/9');
width: 200px;
height: 200px;
/* you need to match the shadow color to your background or image border for the desired effect*/
box-shadow: 0 0 8px 8px white inset;
}
I used a third party library called use-force-update to force render my react functional components. Worked like charm. Just use import the package in your project and use like this.
import useForceUpdate from 'use-force-update';
const MyButton = () => {
const forceUpdate = useForceUpdate();
const handleClick = () => {
alert('I will re-render now.');
forceUpdate();
};
return <button onClick={handleClick} />;
};
You may do the following:
git -m master master-old #rename current master
git checkout -b master #create a new branch master
git push -f origin master #force push to master
But force pushing is a bad idea if other people are sharing this repository. Force push will cause their revision history to conflict with the new one.
first you need to find your python.exe location, to find location run this python script:
import sys
print(sys.executable)
Then you can create your custom python build:
{
"cmd": ["C:\\Users\\Sashi\\AppData\\Local\\Programs\\Python\\Python39\\python.exe", "-u", "$file"],
"file_regex": "^[ ]File \"(...?)\", line ([0-9]*)",
"selector": "source.python"}
You can change the location, In my case it is C:\Users\Sashi\AppData\Local\Programs\Python\Python39\python.exe
Then save your new build. Don't change the file extension while saving.
If you have a large list of extensions to check you can use the following. I didn't want to create a lot of OR statements so i modified what lette wrote.
string supportedExtensions = "*.jpg,*.gif,*.png,*.bmp,*.jpe,*.jpeg,*.wmf,*.emf,*.xbm,*.ico,*.eps,*.tif,*.tiff,*.g01,*.g02,*.g03,*.g04,*.g05,*.g06,*.g07,*.g08";
foreach (string imageFile in Directory.GetFiles(_tempDirectory, "*.*", SearchOption.AllDirectories).Where(s => supportedExtensions.Contains(Path.GetExtension(s).ToLower())))
{
//do work here
}
I just found this error., while using GETDATE() [i.e outer reference] in the group by clause in a select query.
When replaced it with date column from the respective table it cleared.
Thought to share as a simple example. cheers ;)
For those who have Excel 2016 (and I suppose next versions), there is now directly the CONCAT function, which will replace the CONCATENATE function.
So the correct way to do it in Excel 2016 is :
=CONCAT(A1:A4)
which will produce :
Iamaboy
For users of olders versions of Excel, the other answers are relevant.
A simple solution:
original = [1,2,3]
cloned = original.map(x=>x)
Say the hierarchy is C->B->A
with A being the base class.
I think there's more to fixing this than renaming a method. That will work but is that a fix?
One way is to refactor all the functionality common to B and C into D, and let B and C inherit from D: (B,C)->D->A
Now the method in B that was hiding A's implementation from C is specific to B and stays there. This allows C to invoke the method in A without any hokery.
To do that, you must remove all '
charachters in your string or use an escape character. Like:
<?php
echo '<?php
echo \'hello world\';
?>';
?>
It means that the http server at cw.na1.hgncloud.com
send some http headers to tell web browsers like Chrome to allow iframe loading of that page (https://cw.na1.hgncloud.com/crossmatch/) only from a page hosted on the same domain (cw.na1.hgncloud.com) :
Content-Security-Policy: frame-ancestors 'self' https://cw.na1.hgncloud.com
X-Frame-Options: ALLOW-FROM https://cw.na1.hgncloud.com
You should read that :
Try this one.
<Button
android:id="@+id/bSearch"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="16dp"
android:text="Search"
android:drawableLeft="@android:drawable/ic_menu_search"
android:textSize="24sp"/>
If you are using numpy in your code (which might be a good choice for larger amounts of data), check out numpy.unique:
>>> import numpy as np
>>> wordsList = [u'nowplaying', u'PBS', u'PBS', u'nowplaying', u'job', u'debate', u'thenandnow']
>>> np.unique(wordsList)
array([u'PBS', u'debate', u'job', u'nowplaying', u'thenandnow'],
dtype='<U10')
(http://docs.scipy.org/doc/numpy/reference/generated/numpy.unique.html)
As you can see, numpy supports not only numeric data, string arrays are also possible. Of course, the result is a numpy array, but it doesn't matter a lot, because it still behaves like a sequence:
>>> for word in np.unique(wordsList):
... print word
...
PBS
debate
job
nowplaying
thenandnow
If you really want to have a vanilla python list back, you can always call list().
However, the result is automatically sorted, as you can see from the above code fragments. Check out numpy unique without sort if retaining list order is required.
You can also create a HTML alert template like this:
<div class="alert alert-info" id="alert_template" style="display: none;">
<button type="button" class="close">×</button>
</div>
And so you can do in JavaScript this here:
$("#alert_template button").after('<span>Some text</span>');
$('#alert_template').fadeIn('slow');
Which is in my opinion cleaner and faster. In addition you stick to Twitter Bootstrap standards when calling fadeIn()
.
To guarantee that this alert template works also with multiple calls (so it doesn't add the new message to the old one), add this here to your JavaScript:
$('#alert_template .close').click(function(e) {
$("#alert_template span").remove();
});
So this call removes the span element every time you close the alert via the x-button.
try with below on powershell:
Set-ExecutionPolicy -ExecutionPolicy Unrestricted
import-module [\path\]XMLHelpers.psm1
Instead of [] put the full path
For example your file contains :
1. mangesh@001:~$ cat output.txt
1
2
EOF
if u want to append at end of file then ---->remember spaces between 'text' >> 'filename'
2. mangesh@001:~$ echo somthing to append >> output.txt|cat output.txt
1
2
EOF
somthing to append
And to overwrite contents of file :
3. mangesh@001:~$ echo 'somthing new to write' > output.tx|cat output.tx
somthing new to write
This works for me in irb:
irb> (1..4).to_a
=> [1, 2, 3, 4]
I notice that:
irb> 1..4.to_a
(irb):1: warning: default `to_a' will be obsolete
ArgumentError: bad value for range
from (irb):1
So perhaps you are missing the parentheses?
(I am running Ruby 1.8.6 patchlevel 114)
You need to use the jQuery AJAX or XMLHttpRequest() for post the data to the server. After data posting you can redirect your page to another page by window.location.href
.
Example:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
window.location.href = 'https://website.com/my-account';
}
};
xhttp.open("POST", "demo_post.asp", true);
xhttp.send();
I've used this tool before- although it seems like there needs to be an issue open first, it is super useful and really streamlines workflow if you use github issue tracking. git open-pull and then a pull request is submitted from whatever branch you are on or select. https://github.com/jehiah/git-open-pull
EDIT: Looks like you can create issues on the fly, so this tool is a good solution.
Another solution to the problem could be the following set of CSS rules:
.ellipsis{
white-space:nowrap;
overflow:hidden;
}
.ellipsis:after{
content:'...';
}
The only drawback with the above CSS is that it would add the "..." irrespective of whether the text-overflows the container or not. Still, if you have a case where you have a bunch of elements and are sure that content will overflow, this one would be a simpler set of rules.
My two cents. Hats off to the original technique by Justin Maxwell
You can either
fig, ax = plt.subplots() #create figure and axes
candlestick(ax, quotes, ...)
or
candlestick(plt.gca(), quotes) #get the axis when calling the function
The first gives you more flexibility. The second is much easier if candlestick is the only thing you want to plot
Have a read of the urllib Missing Manual. Pulled from there is the following simple example of a POST request.
url = 'http://myserver/post_service'
data = urllib.urlencode({'name' : 'joe', 'age' : '10'})
req = urllib2.Request(url, data)
response = urllib2.urlopen(req)
print response.read()
As suggested by @Michael Kent do consider requests, it's great.
EDIT: This said, I do not know why passing data to urlopen() does not result in a POST request; It should. I suspect your server is redirecting, or misbehaving.
So the problem is that you want to upload a base 64 image and you have a blob url. Now the answer that will work on all html 5 browsers is: Do:
var fileInput = document.getElementById('myFileInputTag');
var preview = document.getElementById('myImgTag');
fileInput.addEventListener('change', function (e) {
var url = URL.createObjectURL(e.target.files[0]);
preview.setAttribute('src', url);
});
function Upload()
{
// preview can be image object or image element
var myCanvas = document.getElementById('MyCanvas');
var ctx = myCanvas.getContext('2d');
ctx.drawImage(preview, 0,0);
var base64Str = myCanvas.toDataURL();
$.ajax({
url: '/PathToServer',
method: 'POST',
data: {
imageString: base64Str
},
success: function(data) { if(data && data.Success) {}},
error: function(a,b,c){alert(c);}
});
}
Simple way i found out was to make a new xml file in the drawable folder and then point the buttons background to that xml file. heres the code i used:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<solid android:color="#ff8100"/>
<corners android:radius="5dp"/>
</shape>
For writing if
statement inline, the code inside of it should only be one statement:
if ( a < b ) // code to be executed without curly braces;
TestGameTable.class.getResource("/unibo/lsb/res/dice.jpg");
getResource()
directly on the class.A character encoding is a way to encode characters so that they fit in memory. That is, if the charset is ISO-8859-15, the euro symbol, €, will be encoded as 0xa4, and in UTF-8, it will be 0xe282ac.
The collation is how to compare characters, in latin9, there are letters as e é è ê f
, if sorted by their binary representation, it will go e f é ê è
but if the collation is set to, for example, French, you'll have them in the order you thought they would be, which is all of e é è ê
are equal, and then f
.
On SQL 2017 - Database A has synonyms to Database B. User can connect to database A and has exec rights to an sp (on A) that refers to the synonyms that point to B. User was set up with connect access B. Only when granting CONNECT to the public group to database B did the sp on A work. I don't recall this working this way on 2012 as granting connect to the user only seemed to work.
If you encounter this error, please read the log file:
$ cat /var/log/cuda-installer.log
[INFO]: Driver installation detected by command: apt list --installed | grep -e nvidia-driver-[0-9][0-9][0-9] -e nvidia-[0-9][0-9][0-9]
[INFO]: Cleaning up window
[INFO]: Complete
[INFO]: Checking compiler version...
[INFO]: gcc location: /usr/bin/gcc
[INFO]: gcc version: gcc version 9.2.1 20191008 (Ubuntu 9.2.1-9ubuntu2)
[ERROR]: unsupported compiler version: 9.2.1. Use --override to override this check.
Just follow the suggestion in the log file:
sudo sh cuda_<version>_linux.run --override
Job done :)
I just installed CUDA 10.2 with gcc 9.2 on Kubuntu 19.10 using the --override
option.
One of the benefit of using the resource file is accessing the resources by names, so the image can change, the image name can change, as long as the resource is kept up to date correct image will show up.
Here is a cleaner approach to accomplish this: Assuming Resources.resx is in 'UI.Images' namespace, add the namespace reference in your xaml like this:
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:UI="clr-namespace:UI.Images"
Set your Image source like this:
<Image Source={Binding {x:Static UI:Resources.Search}} />
where 'Search' is name of the resource.
To parse a date, look at Date::Parse in CPAN.
Use white-space:nowrap
and overflow:hidden
I had the same problem running windows 7-64 with VB6. I tried the unregister and re-register solutions above but it did not solve the problem. Then I noticed that in my VB6 Components I had references to both the Microsoft Windows Common Controls -2 6.0(SP6) and Microsoft Windows Common Controls -3 6.0(SP5). I removed the SP5 reference and all now works OK. It seems that -2 6.0 SP6 supersedes -3 6.0 (SP5) and when both are present there are two references to the same control. Hope this helps. Steve
Simply Try this:
int n = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("data is: {0}", Convert.ToChar(n));
In your Jenkins job configuration, tick the box named "This build is parameterized
", click the "Add Parameter
" button and select the "String Parameter
" drop down value.
Now define your parameter - example:
Now you can use your parameter in your job / build pipeline, example:
Next to trigger the build with own/custom parameter, invoke the following URL (using either POST or GET):
http://JENKINS_SERVER_ADDRESS/job/YOUR_JOB_NAME/buildWithParameters?myparam=myparam_value
Also, to note - the Active Record Class also has a $this->db->where_in()
method.
You have to put your SDK's in a given directory or .app directory. You have to do it in finder while you are out of the application i'm assuming, but personally I'd use terminal in Mac instead of doing it in the App itself or finder. According to Google:
On Windows and Mac, the individual tools and other SDK packages are saved within the Android Studio application directory. To access the tools directly, use a terminal to navigate into the application and locate the sdk/ directory. For example:
Windows: \Users\<user>\AppData\Local\Android\android-studio\sdk\
Mac: /Applications/Android\ Studio.app/sdk/
First off: My problem isn't the exact same as yours, but this post is the first thing that comes up in google for the Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'
error at the time I wrote this. The solution may be useful to people searching for this error as I did not find this specific solution anywhere online.
In my case, I used Xampp/Apache and PHP sqlsrv to try to connect to an MSSQL database using Windows Authentication and received the Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'
error you described. I finally found the problem to be the Apache service itself running under the user "LOCAL SERVICE" instead of the user account I was logged in as. In other words, it literally was using an anonymous account. The solution was to go into services.msc, right click the Apache service, go to Properties, go to the Log On tab, and enter the credentials for the user. This falls in line with your problem related to SPN's as your SPN's are set up to run from a specific user on the domain. So if the correct SPN is not running, windows authentication will default to the wrong user (likely the "LOCAL SERVICE" user) and give you the Anonymous error.
Here's where it's different from your problem. None of the computers on the local network are on a Domain, they are only on a Workgroup. To use Windows Authentication with a Workgroup, both the computer with the server (in my case MSSQL Server) and the computer with the service requesting data (in my case Apache) needed to have a user with an identical name and identical password.
To summarize, The Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'
error in both our cases seems to be caused by a service not running and/or not on the right user. Ensuring the right SPN or other Service is running and under the correct user should solve the anonymous part of the problem.
For what it's worth my issue was that the files themselves were in the wrong encoding. Using iconv worked for me
iconv -f ISO-8859-15 -t UTF-8 messages_nl.properties > messages_nl.properties.new
It was pretty exciting to make this method work, so it makes a clone of a function using Function call.
Some limitations about closures described at MDN Function Reference
function cloneFunc( func ) {
var reFn = /^function\s*([^\s(]*)\s*\(([^)]*)\)[^{]*\{([^]*)\}$/gi
, s = func.toString().replace(/^\s|\s$/g, '')
, m = reFn.exec(s);
if (!m || !m.length) return;
var conf = {
name : m[1] || '',
args : m[2].replace(/\s+/g,'').split(','),
body : m[3] || ''
}
var clone = Function.prototype.constructor.apply(this, [].concat(conf.args, conf.body));
return clone;
}
Enjoy.
How about:
if (new[] {1, 2}.Contains(value))
It's a hack though :)
Or if you don't mind creating your own extension method, you can create the following:
public static bool In<T>(this T obj, params T[] args)
{
return args.Contains(obj);
}
And you can use it like this:
if (1.In(1, 2))
:)
This code works for me. When keyboard appears, you can scroll screen
In AndroidManifest.xml
<activity android:name=".signup.screen_2.SignUpNameAndPasswordActivity"
android:screenOrientation="portrait"
android:windowSoftInputMode="adjustResize">
</activity>
activity_sign_up.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true"
tools:context=".signup.screen_2.SignUpNameAndPasswordActivity">
<LinearLayout
android:fitsSystemWindows="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_marginTop="@dimen/dp_24"
android:layout_marginStart="@dimen/dp_24"
android:layout_marginEnd="@dimen/dp_24"
android:id="@+id/lin_name_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:fontFamily="sans-serif-medium"
android:text="@string/name_and_password"
android:textColor="@color/colorBlack"
android:layout_marginTop="@dimen/dp_5"
android:textSize="@dimen/ts_16"/>
<EditText
android:id="@+id/edit_full_name"
android:layout_width="match_parent"
android:layout_height="@dimen/dp_44"
app:layout_constraintTop_toTopOf="parent"
android:hint="@string/email_address_hint"
android:inputType="textPersonName"
android:imeOptions="flagNoFullscreen"
android:textSize="@dimen/ts_15"
android:background="@drawable/rounded_border_edittext"
android:layout_marginTop="@dimen/dp_15"
android:paddingStart="@dimen/dp_8"
android:paddingEnd="@dimen/dp_8"
android:maxLength="100"
android:maxLines="1"/>
<EditText
android:id="@+id/edit_password"
android:layout_width="match_parent"
android:layout_height="@dimen/dp_44"
app:layout_constraintTop_toTopOf="parent"
android:hint="@string/password"
android:inputType="textPassword"
android:imeOptions="flagNoFullscreen"
android:textSize="@dimen/ts_15"
android:background="@drawable/rounded_border_edittext"
android:layout_marginTop="@dimen/dp_15"
android:paddingStart="@dimen/dp_8"
android:paddingEnd="@dimen/dp_8"
android:maxLength="100"
android:maxLines="1"/>
<TextView
android:id="@+id/btn_continue_and_sync_contacts"
android:layout_width="match_parent"
android:layout_height="@dimen/dp_44"
android:gravity="center"
android:clickable="true"
android:focusable="true"
android:layout_marginTop="@dimen/dp_15"
android:background="@drawable/btn_blue_selector"
android:enabled="false"
android:text="@string/continue_and_sync_contacts"
android:textColor="@color/colorWhite"
android:textSize="@dimen/ts_15"
android:textStyle="bold"/>
<TextView
android:id="@+id/btn_continue_without_syncing_contacts"
android:layout_width="match_parent"
android:layout_height="@dimen/dp_44"
android:gravity="center"
android:clickable="true"
android:focusable="true"
android:layout_marginTop="@dimen/dp_10"
android:enabled="false"
android:text="@string/continue_without_syncing_contacts"
android:textColor="@color/colorBlue"
android:textSize="@dimen/ts_15"
android:textStyle="bold"/>
</LinearLayout>
<!--RelativeLayout is scaled when keyboard appears-->
<RelativeLayout
android:layout_marginStart="@dimen/dp_24"
android:layout_marginEnd="@dimen/dp_24"
android:layout_marginBottom="@dimen/dp_20"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_alignParentBottom="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/tv_learn_more_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
android:focusable="true"
android:layout_gravity="center_horizontal"
android:text="@string/learn_more_syncing_contacts"
android:textColor="@color/black_alpha_70"
android:gravity="center"
android:layout_marginBottom="1dp"
android:textSize="@dimen/ts_13"/>
<TextView
android:id="@+id/tv_learn_more_2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
android:focusable="true"
android:layout_gravity="center_horizontal"
android:text="@string/learn_more"
android:fontFamily="sans-serif-medium"
android:textColor="@color/black_alpha_70"
android:textSize="@dimen/ts_13"/>
</LinearLayout>
</RelativeLayout>
</LinearLayout>
</ScrollView>
rounded_border_edittext.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_activated="true">
<shape android:shape="rectangle">
<solid android:color="#F6F6F6"/>
<corners android:radius="3dp"/>
<stroke
android:width="1dp"
android:color="@color/red"/>
</shape>
</item>
<item android:state_activated="false">
<shape android:shape="rectangle">
<solid android:color="#F6F6F6"/>
<corners android:radius="3dp"/>
<stroke
android:width="1dp"
android:color="@color/colorGray"/>
</shape>
</item>
</selector>
btn_blue_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_enabled="true" android:state_pressed="true">
<shape android:shape="rectangle">
<corners android:radius="3dp"/>
<solid android:color="@color/colorBlueLight"/>
<stroke android:width="1dp" android:color="@color/colorBlueLight"/>
</shape>
</item>
<item android:state_enabled="true">
<shape android:shape="rectangle">
<corners android:radius="3dp"/>
<solid android:color="@color/colorBlue"/>
<stroke android:width="1dp" android:color="@color/colorBlue"/>
</shape>
</item>
<item android:state_enabled="false">
<shape android:shape="rectangle">
<corners android:radius="3dp"/>
<solid android:color="@color/colorBlueAlpha"/>
<stroke android:width="0dp" android:color="@color/colorBlueAlpha"/>
</shape>
</item>
</selector>
It is not a good practice but even though you wish to use it you can use the singleton pattern as its good. I have used the singleton patterns in most of my project its good.
You can easily normalize the data also using data.Normalization function in clusterSim package. It provides different method of data normalization.
data.Normalization (x,type="n0",normalization="column")
Arguments
x
vector, matrix or dataset
type
type of normalization:
n0 - without normalization
n1 - standardization ((x-mean)/sd)
n2 - positional standardization ((x-median)/mad)
n3 - unitization ((x-mean)/range)
n3a - positional unitization ((x-median)/range)
n4 - unitization with zero minimum ((x-min)/range)
n5 - normalization in range <-1,1> ((x-mean)/max(abs(x-mean)))
n5a - positional normalization in range <-1,1> ((x-median)/max(abs(x-median)))
n6 - quotient transformation (x/sd)
n6a - positional quotient transformation (x/mad)
n7 - quotient transformation (x/range)
n8 - quotient transformation (x/max)
n9 - quotient transformation (x/mean)
n9a - positional quotient transformation (x/median)
n10 - quotient transformation (x/sum)
n11 - quotient transformation (x/sqrt(SSQ))
n12 - normalization ((x-mean)/sqrt(sum((x-mean)^2)))
n12a - positional normalization ((x-median)/sqrt(sum((x-median)^2)))
n13 - normalization with zero being the central point ((x-midrange)/(range/2))
normalization
"column" - normalization by variable, "row" - normalization by object
This sounds like a ClassLoader conflict. I'd bet you have the javax.persistence api 1.x on the classpath somewhere, whereas Spring is trying to access ValidationMode
, which was only introduced in JPA 2.0.
Since you use Maven, do mvn dependency:tree
, find the artifact:
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>persistence-api</artifactId>
<version>1.0</version>
</dependency>
And remove it from your setup. (See Excluding Dependencies)
AFAIK there is no such general distribution for JPA 2, but you can use this Hibernate-specific version:
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.0-api</artifactId>
<version>1.0.1.Final</version>
</dependency>
OK, since that doesn't work, you still seem to have some JPA-1 version in there somewhere. In a test method, add this code:
System.out.println(EntityManager.class.getProtectionDomain()
.getCodeSource()
.getLocation());
See where that points you and get rid of that artifact.
Ahh, now I finally see the problem. Get rid of this:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jpa</artifactId>
<version>2.0.8</version>
</dependency>
and replace it with
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>3.2.5.RELEASE</version>
</dependency>
On a different note, you should set all test libraries (spring-test, easymock etc.) to
<scope>test</scope>
Remove everything, but this:
Align(
alignment: Alignment.bottomCenter,
child: new ButtonBar(
alignment: MainAxisAlignment.center,
children: <Widget>[
new OutlineButton(
onPressed: () {
Navigator.push(
context,
new MaterialPageRoute(
builder: (context) => new LoginPage()));
},
child: new Text(
"Login",
style: new TextStyle(color: Colors.white),
),
),
new RaisedButton(
color: Colors.white,
onPressed: () {
Navigator.push(
context,
new MaterialPageRoute(
builder: (context) =>
new RegistrationPage()));
},
child: new Text(
"Register",
style: new TextStyle(color: Colors.black),
),
)
],
),
)
In my theory, the additional Container
is destroying it. I would advise you to just surround this by adding Padding
:
Padding(
padding: EdgeInsets.only(bottom: 20.0),
child: Align...
),
This seems a lot more reasonable to me than the Positioned
and also I do not quite understand your Column
with a single child only.
Also see the speeded-up package ujson:
import ujson
with open('data.json', 'wb') as fp:
ujson.dump(data, fp)
You can use recursion here to do this. For example:
jQuery(document).ready(checkContainer);
function checkContainer () {
if($('#divIDer').is(':visible'))){ //if the container is visible on the page
createGrid(); //Adds a grid to the html
} else {
setTimeout(checkContainer, 50); //wait 50 ms, then try again
}
}
Basically, this function will check to make sure that the element exists and is visible. If it is, it will run your createGrid()
function. If not, it will wait 50ms and try again.
Note:: Ideally, you would just use the callback function of your AJAX call to know when the container was appended, but this is a brute force, standalone approach. :)
The other answers and comments covered table renaming, file renaming, and grepping through your code.
I'd like to add a few more caveats:
Let's use a real-world example I faced today: renaming a model from 'Merchant' to 'Business.'
(5 years laters, for the Honor of PostgreSQL, the most advanced DDBB of the Kingdom)
In PostgreSQL:
\d table_name
Or, using SQL:
select column_name, data_type, character_maximum_length
from INFORMATION_SCHEMA.COLUMNS
where table_name = 'table_name';
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
return headers;
}
You need to add Content-Type to the header.
For Windows users.
This happens because the MondgDB server is stopped. to fix this you can,
1 search for Services ,for that search using the left bottom corner search option.
2 then there is a gear icon named with 'Services'.
3 after clicking that you will get a window with lot of services
4 scroll down and you will find 'MongoDB server (MongoDB)'.
5 so you will see that there is an option to start the service.
6 start it.
1 then open your command prompt.
2 type mongod
now you can connect to your server.
this steps also working fine if your sql server service down. (find sql server services)
http://www.jstott.me.uk/jcoord/ - use this library
LatLng lld1 = new LatLng(40.718119, -73.995667);
LatLng lld2 = new LatLng(51.499981, -0.125313);
Double distance = lld1.distance(lld2);
Log.d(TAG, "Distance in kilometers " + distance);
This is what I did.
$('.selectpicker').on('changed.bs.select', function (e, clickedIndex, newValue, oldValue) {
var selected = $(e.currentTarget).val();
});
char members[255] = {0};
You might want to use raw.githack.com. It supports GitHub, Bitbucket, Gitlab and GitHub gists.
https://raw.githubusercontent.com/[user]/[repository]/[branch]/[filename.ext]
In your case .html
extension
Development (throttled)
https://raw.githack.com/[user]/[repository]/[branch]/[filename.ext]
Production (CDN)
https://rawcdn.githack.com/[user]/[repository]/[branch]/[filename.ext]
In your case .html
extension
raw.githack.com also supports other services:
https://bitbucket.org/[user]/[repository]/raw/[branch]/[filename.ext]
Development (throttled)
https://bb.githack.com/[user]/[repository]/raw/[branch]/[filename.ext]
Production (CDN)
https://bbcdn.githack.com/[user]/[repository]/raw/[branch]/[filename.ext]
https://gitlab.com/[user]/[repository]/raw/[branch]/[filename.ext]
Development (throttled)
https://gl.githack.com/[user]/[repository]/raw/[branch]/[filename.ext]
Production (CDN)
https://glcdn.githack.com/[user]/[repository]/raw/[branch]/[filename.ext]
https://gist.githubusercontent.com/[user]/[gist]/raw/[revision]/[filename.ext]
Development (throttled)
https://gist.githack.com/[user]/[gist]/raw/[revision]/[filename.ext]
Production (CDN)
https://gistcdn.githack.com/[user]/[gist]/raw/[revision]/[filename.ext]
Update: rawgit was discontinued
Yes you can...
WITH SET1 AS (SELECT SYSDATE FROM DUAL), -- SET1 initialised
SET2 AS (SELECT * FROM SET1) -- SET1 accessed
SELECT * FROM SET2; -- SET2 projected
10/29/2013 10:43:26 AM
Follow the order in which it should be initialized in Common Table Expressions
Having following html:
<!-- note that not all browsers focus on links when Tab is pressed -->
<a href="http://example.com">Link</a>
<input type="text" placeholder="Some input" />
<a href="http://example.com">Another Link</a>
<textarea>...</textarea>
You can get to active link with:
// event listener for keyup
function checkTabPress(e) {
"use strict";
// pick passed event or global event object if passed one is empty
e = e || event;
var activeElement;
if (e.keyCode == 9) {
// Here read the active selected link.
activeElement = document.activeElement;
// If HTML element is an anchor <a>
if (activeElement.tagName.toLowerCase() == 'a')
// get it's hyperlink
alert(activeElement.href);
}
}
var body = document.querySelector('body');
body.addEventListener('keyup', checkTabPress);
Here is working example.
set ORACLE_SID=<YOUR_SID>
sqlplus "/as sysdba"
alter system disable restricted session;
or maybe
shutdown abort;
or maybe
lsnrctl stop
lsnrctl start
Wrapping components with braces if no default exports:
import {MyNavbar} from './comp/my-navbar.jsx';
or import multiple components from single module file
import {MyNavbar1, MyNavbar2} from './module';
This is an extension to Langdon's answer with a directive approach to the problem. If you're going to have multiple galleries on the page this may be one way to go about it without much fuss.
Usage:
<gallery images="items"></gallery>
<gallery images="cats"></gallery>
This is the code I'm using. Also works for .NET Core
> 2.0 using System.Drawing.Common
NuGet.
https://www.nuget.org/packages/System.Drawing.Common/
using System;
using System.Drawing;
class Program
{
static void Main()
{
const string input = "C:\\background1.png";
const string output = "C:\\thumbnail.png";
// Load image.
Image image = Image.FromFile(input);
// Compute thumbnail size.
Size thumbnailSize = GetThumbnailSize(image);
// Get thumbnail.
Image thumbnail = image.GetThumbnailImage(thumbnailSize.Width,
thumbnailSize.Height, null, IntPtr.Zero);
// Save thumbnail.
thumbnail.Save(output);
}
static Size GetThumbnailSize(Image original)
{
// Maximum size of any dimension.
const int maxPixels = 40;
// Width and height.
int originalWidth = original.Width;
int originalHeight = original.Height;
// Return original size if image is smaller than maxPixels
if (originalWidth <= maxPixels || originalHeight <= maxPixels)
{
return new Size(originalWidth, originalHeight);
}
// Compute best factor to scale entire image based on larger dimension.
double factor;
if (originalWidth > originalHeight)
{
factor = (double)maxPixels / originalWidth;
}
else
{
factor = (double)maxPixels / originalHeight;
}
// Return thumbnail size.
return new Size((int)(originalWidth * factor), (int)(originalHeight * factor));
}
}
Source:
This is way I did it:
%matplotlib inline
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = (12, 9) # (w, h)
You can define your own sizes.
You should not be setting the class of your view controller to be a subclass of UIView
in Interface Builder. That is most definitely at least part of your problem. Leave that as either UIViewController
, some subclass of it, or some other custom class you have.
As for loading only a view from a xib, I was under the assumption that you had to have some sort of view controller (even if it doesn't extend UIViewController
, which may be too heavyweight for your needs) set as the File's Owner in Interface Builder if you want to use it to define your interface. I did a little research to confirm this as well. This is because otherwise there would be no way to access any of the interface elements in the UIView
, nor would there be a way to have your own methods in code be triggered by events.
If you use a UIViewController
as your File's Owner for your views, you can just use initWithNibName:bundle:
to load it and get the view controller object back. In IB, make sure you set the view
outlet to the view with your interface in the xib. If you use some other type of object as your File's Owner, you'll need to use NSBundle
's loadNibNamed:owner:options:
method to load the nib, passing an instance of File's Owner to the method. All its properties will be set properly according to the outlets you define in IB.
Use setBackgroundResource(R.drawable.xml/png)
I used maptoInt() with Lambda operation for converting string to Integer
int[] arr = Arrays.stream(stringArray).mapToInt(item -> Integer.parseInt(item)).toArray();
C# and the CLR should support static methods in interfaces as Java does. The static modifier is part of a contract definition and does have meaning, specifically that the behavior and return value do not vary base on instance although it may still vary from call to call.
That said, I recommend that when you want to use a static method in an interface and cannot, use an annotation instead. You will get the functionality you are looking for.
With JAXB, you could use the code below:
@Test
public void testCheckXmlIsValidAgainstSchema() {
logger.info("Validating an XML file against the latest schema...");
MyValidationEventCollector vec = new MyValidationEventCollector();
validateXmlAgainstSchema(vec, inputXmlFileName, inputXmlSchemaName, inputXmlRootClass);
assertThat(vec.getValidationErrors().isEmpty(), is(expectedValidationResult));
}
private void validateXmlAgainstSchema(final MyValidationEventCollector vec, final String xmlFileName, final String xsdSchemaName, final Class<?> rootClass) {
try (InputStream xmlFileIs = Thread.currentThread().getContextClassLoader().getResourceAsStream(xmlFileName);) {
final JAXBContext jContext = JAXBContext.newInstance(rootClass);
// Unmarshal the data from InputStream
final Unmarshaller unmarshaller = jContext.createUnmarshaller();
final SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
final InputStream schemaAsStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(xsdSchemaName);
unmarshaller.setSchema(sf.newSchema(new StreamSource(schemaAsStream)));
unmarshaller.setEventHandler(vec);
unmarshaller.unmarshal(new StreamSource(xmlFileIs), rootClass).getValue(); // The Document class is the root object in the XML file you want to validate
for (String validationError : vec.getValidationErrors()) {
logger.trace(validationError);
}
} catch (final Exception e) {
logger.error("The validation of the XML file " + xmlFileName + " failed: ", e);
}
}
class MyValidationEventCollector implements ValidationEventHandler {
private final List<String> validationErrors;
public MyValidationEventCollector() {
validationErrors = new ArrayList<>();
}
public List<String> getValidationErrors() {
return Collections.unmodifiableList(validationErrors);
}
@Override
public boolean handleEvent(final ValidationEvent event) {
String pattern = "line {0}, column {1}, error message {2}";
String errorMessage = MessageFormat.format(pattern, event.getLocator().getLineNumber(), event.getLocator().getColumnNumber(),
event.getMessage());
if (event.getSeverity() == ValidationEvent.FATAL_ERROR) {
validationErrors.add(errorMessage);
}
return true; // you collect the validation errors in a List and handle them later
}
}
The exec
family of functions make your process execute a different program, replacing the old program it was running. I.e., if you call
execl("/bin/ls", "ls", NULL);
then the ls
program is executed with the process id, current working dir and user/group (access rights) of the process that called execl
. Afterwards, the original program is not running anymore.
To start a new process, the fork
system call is used. To execute a program without replacing the original, you need to fork
, then exec
.
You can use Apache Commons' StringUtils.countMatches(String string, String subStringToCount)
.
RealVNC 5.0.x now offers a VNCViewer that will do dual displays on Windows without having to buy a license. (Licensing now covers the SERVER portion of their tools).
In Angular (currently on Angular-6) .subscribe()
is a method on the Observable type. The Observable type is a utility that asynchronously or synchronously streams data to a variety of components or services that have subscribed to the observable.
The observable is an implementation/abstraction over the promise chain and will be a part of ES7 as a proposed and very supported feature. In Angular it is used internally due to rxjs being a development dependency.
An observable itself can be thought of as a stream of data coming from a source, in Angular this source is an API-endpoint, a service, a database or another observable. But the power it has is that it's not expecting a single response. It can have one or many values that are returned.
Link to rxjs for observable/subscribe docs here: https://rxjs-dev.firebaseapp.com/api/index/class/Observable#subscribe-
Subscribe takes 3 methods as parameters each are functions:
Within each of these, there is the potentional to pipe (or chain) other utilities called operators onto the results to change the form or perform some layered logic.
In the simple example above:
.subscribe(hero => this.hero = hero);
basically says on this observable take the hero being emitted and set it to this.hero
.
Adding this answer to give more context to Observables based off the documentation and my understanding.
As of Entity Framework 4.3, there is an AddOrUpdate
method at namespace System.Data.Entity.Migrations
:
public static void AddOrUpdate<TEntity>(
this IDbSet<TEntity> set,
params TEntity[] entities
)
where TEntity : class
which by the doc:
Adds or updates entities by key when SaveChanges is called. Equivalent to an "upsert" operation from database terminology. This method can be useful when seeding data using Migrations.
To answer the comment by @Smashing1978, I will paste relevant parts from link provided by @Colin
The job of AddOrUpdate is to ensure that you don’t create duplicates when you seed data during development.
First, it will execute a query in your database looking for a record where whatever you supplied as a key (first parameter) matches the mapped column value (or values) supplied in the AddOrUpdate. So this is a little loosey-goosey for matching but perfectly fine for seeding design time data.
More importantly, if a match is found then the update will update all and null out any that weren’t in your AddOrUpdate.
That said, I have a situation where I am pulling data from an external service and inserting or updating existing values by primary key (and my local data for consumers is read-only) - been using AddOrUpdate
in production for more than 6 months now and so far no problems.
Another option is to check if it's busy with a timer:
Set the timer as disabled by default. Then whenever navigating, enable it. i.e.:
WebBrowser1.Navigate("https://www.somesite.com")
tmrBusy.Enabled = True
And the timer:
Private Sub tmrBusy_Tick(sender As Object, e As EventArgs) Handles tmrBusy.Tick
If WebBrowser1.IsBusy = True Then
Debug.WriteLine("WB Busy ...")
Else
Debug.WriteLine("WB Done.")
tmrBusy.Enabled = False
End If
End Sub
EDIT Step 1) Go to File > Project Structure > select project > go to "signing" and select your default or any keystore you want and fill all the details. In case you are not able to fill the details, hit the green '+' button. I've highlighted in the screenshot.
Step 2) VERY IMPORTANT: Goto Build Types> select your build type and select your "Signing Config". In my case, I've to select "config". Check the highlighted region.
You can also use the 'sed' function that's part of ShellJS ...
$ npm install [-g] shelljs
require('shelljs/global');
sed('-i', 'search_pattern', 'replace_pattern', file);
Visit ShellJs.org for more examples.
Another way is using 'HttpClient' like this:
using System;
using System.Net;
using System.Net.Http;
namespace Test
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Making API Call...");
using (var client = new HttpClient(new HttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate }))
{
client.BaseAddress = new Uri("https://api.stackexchange.com/2.2/");
HttpResponseMessage response = client.GetAsync("answers?order=desc&sort=activity&site=stackoverflow").Result;
response.EnsureSuccessStatusCode();
string result = response.Content.ReadAsStringAsync().Result;
Console.WriteLine("Result: " + result);
}
Console.ReadLine();
}
}
}
Check HttpClient vs HttpWebRequest from stackoverflow and this from other.
Update June 22, 2020: It's not recommended to use httpclient in a 'using' block as it might cause port exhaustion.
private static HttpClient client = null;
ContructorMethod()
{
if(client == null)
{
HttpClientHandler handler = new HttpClientHandler()
{
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
};
client = new HttpClient(handler);
}
client.BaseAddress = new Uri("https://api.stackexchange.com/2.2/");
HttpResponseMessage response = client.GetAsync("answers?order=desc&sort=activity&site=stackoverflow").Result;
response.EnsureSuccessStatusCode();
string result = response.Content.ReadAsStringAsync().Result;
Console.WriteLine("Result: " + result);
}
If using .Net Core 2.1+, consider using IHttpClientFactory and injecting like this in your startup code.
var timeout = Policy.TimeoutAsync<HttpResponseMessage>(
TimeSpan.FromSeconds(60));
services.AddHttpClient<XApiClient>().ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler
{
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
}).AddPolicyHandler(request => timeout);
Your guess is the correct one. The only thing you have to remember is that the member function template definition (in addition to the declaration) should be in the header file, not the cpp, though it does not have to be in the body of the class declaration itself.