Use this function to find all script elements containing some word and refresh them.
function forceReloadJS(srcUrlContains) {_x000D_
$.each($('script:empty[src*="' + srcUrlContains + '"]'), function(index, el) {_x000D_
var oldSrc = $(el).attr('src');_x000D_
var t = +new Date();_x000D_
var newSrc = oldSrc + '?' + t;_x000D_
_x000D_
console.log(oldSrc, ' to ', newSrc);_x000D_
_x000D_
$(el).remove();_x000D_
$('<script/>').attr('src', newSrc).appendTo('head');_x000D_
});_x000D_
}_x000D_
_x000D_
forceReloadJS('/libs/');
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
_x000D_
Try this , there is no need to set its a CLOB
public static void main(String[] args)
{
try{
System.out.println("Opening db");
Class.forName("oracle.jdbc.driver.OracleDriver");
if(con==null)
con=DriverManager.getConnection("jdbc:oracle:thin:@192.9.200.103:1521: orcl","sas","sas");
if(stmt==null)
stmt=con.createStatement();
int res=9;
String usersSql = "{call Esme_Insertsmscdata(?,?,?,?,?)}";
CallableStatement stmt = con.prepareCall(usersSql);
// THIS THE CLOB DATA
stmt.setString(1,"SS¶5268771¶00058711¶04192018¶SS¶5268771¶00058712¶04192018¶SS¶5268772¶00058713¶04192018¶SS¶5268772¶00058714¶04192018¶SS¶5268773¶00058715¶04192018¶SS¶5268773¶00058716¶04192018¶SS¶5268774¶00058717¶04192018¶SS¶5268774¶00058718¶04192018¶SS¶5268775¶00058719¶04192018¶SS¶5268775¶00058720¶04192018¶");
stmt.setString(2, "bcvbcvb");
stmt.setString(3, String.valueOf("4522"));
stmt.setString(4, "42.25.632.25");
stmt.registerOutParameter(5,OracleTypes.NUMBER);
stmt.execute();
res=stmt.getInt(5);
stmt.close();
System.out.println(res);
}
catch(Exception e)
{
try
{
con.close();
} catch (SQLException e1) {
}
}
}
}
You have to set to element_blank()
in theme()
elements you need to remove
ggplot(data = diamonds, mapping = aes(x = clarity)) + geom_bar(aes(fill = cut))+
theme(axis.title.x=element_blank(),
axis.text.x=element_blank(),
axis.ticks.x=element_blank())
The standard way is to use format string modifiers. These format string methods are available in most programming languages (via the sprintf function in c for example) and are a handy tool to know about.
To output a string of length 5:
... in Python 3.5 and above:
i = random.randint(0, 99999)
print(f'{i:05d}')
... Python 2.6 and above:
print '{0:05d}'.format(i)
... before Python 2.6:
print "%05d" % i
I have downloaded the datepicker from jqueryui.com/download and I got 1.7.2 version but still onSelect function didn't work. Here is what i had -
$("#datepicker").datepicker();
$("#datepicker").datepicker({
onSelect: function(value, date) {
alert('The chosen date is ' + value);
}
});
I found the solution in this page -- problem with jquery datepicker onselect . Removed the $("#datepicker").datepicker(); once and it worked.
Can't you originally get the data as a JSONObject?
Perhaps parse the string as both a JSONObject and a JSONArray in the first place? Where is the JSON string coming from?
I'm not sure that it is possible to convert a JsonArray into a JsonObject.
I presume you are using the following from json.org
JSONObject.java
A JSONObject is an unordered collection of name/value pairs. Its external form is a string wrapped in curly braces with colons between the names and values, and commas between the values and names. The internal form is an object having get() and opt() methods for accessing the values by name, and put() methods for adding or replacing values by name. The values can be any of these types: Boolean, JSONArray, JSONObject, Number, and String, or the JSONObject.NULL object.
JSONArray.java
A JSONArray is an ordered sequence of values. Its external form is a string wrapped in square brackets with commas between the values. The internal form is an object having get() and opt() methods for accessing the values by index, and put() methods for adding or replacing values. The values can be any of these types: Boolean, JSONArray, JSONObject, Number, and String, or the JSONObject.NULL object.
More common and simple as for me, suppose you need to count files of different name extensions (say, also natives):
wc $(find . -type f | egrep "\.(h|c|cpp|php|cc)" )
I think this should be a comment or an edit to ThinkingMedia's answer on this very question (Check free disk space for current partition in bash), but I am not allowed to comment (not enough rep) and my edit has been rejected (reason: "this should be a comment or an answer"). So please, powers of the SO universe, don't damn me for repeating and fixing someone else's "answer". But someone on the internet was wrong!™ and they wouldn't let me fix it.
The code
df --output=avail -h "$PWD" | sed '1d;s/[^0-9]//g'
has a substantial flaw:
Yes, it will output 50G
free as 50 -- but it will also output 5.0M
free as 50 or 3.4G
free as 34 or 15K
free as 15.
To create a script with the purpose of checking for a certain amount of free disk space you have to know the unit you're checking against. Remove it (as sed
does in the example above) the numbers don't make sense anymore.
If you actually want it to work, you will have to do something like:
FREE=`df -k --output=avail "$PWD" | tail -n1` # df -k not df -h
if [[ $FREE -lt 10485760 ]]; then # 10G = 10*1024*1024k
# less than 10GBs free!
fi;
Also for an installer to df -k $INSTALL_TARGET_DIRECTORY
might make more sense than df -k "$PWD"
.
Finally, please note that the --output
flag is not available in every version of df / linux.
You can easy get that effect without using jQueryUI, for example:
$(document).ready(function(){
$('#slide').click(function(){
var hidden = $('.hidden');
if (hidden.hasClass('visible')){
hidden.animate({"left":"-1000px"}, "slow").removeClass('visible');
} else {
hidden.animate({"left":"0px"}, "slow").addClass('visible');
}
});
});
Try this working Fiddle:
Here is how you allow extra HTTP Verbs using the IIS Manager GUI.
In IIS Manager, select the site you wish to allow PUT or DELETE for.
Click the "Request Filtering" option. Click the "HTTP Verbs" tab.
Click the "Allow Verb..." link in the sidebar.
In the box that appears type "DELETE", click OK.
Click the "Allow Verb..." link in the sidebar again.
In the box that appears type "PUT", click OK.
Methods in other answers throw OverflowException
if the float value is outside the Int range. https://docs.microsoft.com/en-us/dotnet/api/system.convert.toint32?view=netframework-4.8#System_Convert_ToInt32_System_Single_
int result = 0;
try {
result = Convert.ToInt32(value);
}
catch (OverflowException) {
if (value > 0) result = int.MaxValue;
else result = int.Minvalue;
}
As someone who worked extensively on payment platforms, including one mobile payments application (MyCheck), I would say that you need to delegate this behaviour to the server, no user name or password for the payment processor (whichever it is) should be stored or hardcoded in the mobile application, that's the last thing you want, because the source can be understood even when if you obfuscate the code.
Also, you shouldn't store credit cards or payment tokens on the application, everything should be, again, delegated to a service you built, it will also allow you later on, be PCI-compliant more easily, and the Credit Card companies won't breath down your neck (like they did for us).
This is partially pseudocode, but you will want something like:
rows = ActiveSheet.UsedRange.Rows
n = 0
while n <= rows
if ActiveSheet.Rows(n).Cells(DateColumnOrdinal).Value > '8/1/08' AND < '8/30/08' then
ActiveSheet.Rows(n).CopyTo(DestinationSheet)
endif
n = n + 1
wend
First off, your trigger as you already see is going to update every record in the table. There is no filtering done to accomplish jus the rows changed.
Secondly, you're assuming that only one row changes in the batch which is incorrect as multiple rows could change.
The way to do this properly is to use the virtual inserted and deleted tables: http://msdn.microsoft.com/en-us/library/ms191300.aspx
if you make constructor asynchronous, after creating an object, you may fall into problems like null values instead of instance objects. For instance;
MyClass instance = new MyClass();
instance.Foo(); // null exception here
That's why they don't allow this i guess.
The name open addressing refers to the fact that the location ("address") of the element is not determined by its hash value. (This method is also called closed hashing).
In separate chaining, each bucket is independent, and has some sort of ADT (list, binary search trees, etc) of entries with the same index. In a good hash table, each bucket has zero or one entries, because we need operations of order O(1) for insert, search, etc.
This is a example of separate chaining using C++ with a simple hash function using mod operator (clearly, a bad hash function)
If i understood correct try this one
$headers = "Bcc: [email protected]";
or
$headers = "Cc: [email protected]";
titleForHeaderInSection is a delegate method of UITableView so to apply header text of section write as follows,
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
return @"Hello World";
}
as i also wanted that same thing in a project u can do something like
HTML
<div class="col-md-6"></div>
<div class="divider-vertical"></div>
<div class="col-md-5"></div>
CSS
.divider-vertical {
height: 100px; /* any height */
border-left: 1px solid gray; /* right or left is the same */
float: left; /* so BS grid doesn't break */
opacity: 0.5; /* optional */
margin: 0 15px; /* optional */
}
LESS
.divider-vertical(@h:100, @opa:1, @mar:15) {
height: unit(@h,px); /* change it to rem,em,etc.. */
border-left: 1px solid gray;
float: left;
opacity: @opa;
margin: 0 unit(@mar,px); /* change it to rem,em,etc.. */
}
Don't really think there is some direct method to get the last day but you could do something like this:
var dateInst = new moment();
/**
* adding 1 month from the present month and then subtracting 1 day,
* So you would get the last day of this month
*/
dateInst.add(1, 'months').date(1).subtract(1, 'days');
/* printing the last day of this month's date */
console.log(dateInst.format('YYYY MM DD'));
Here is my slighly different code, solving also the encoding issue:
public string TranslateText(string input, string languagePair)
{
string url = String.Format("http://www.google.com/translate_t?hl=en&ie=UTF8&text={0}&langpair={1}", input, languagePair);
WebClient webClient = new WebClient();
webClient.Encoding = System.Text.Encoding.Default;
string result = webClient.DownloadString(url);
result = result.Substring(result.IndexOf("TRANSLATED_TEXT"));
result = result.Substring(result.IndexOf("'")+1);
result = result.Substring(0, result.IndexOf("'"));
return result;
}
Example of the function call:
var input_language = "en";
var output_language = "es";
var result = TranslateText("Hello", input_language + "|" + output_language);
The result will be "Hola"
private Parcelable state;
@Override
public void onPause() {
state = mAlbumListView.onSaveInstanceState();
super.onPause();
}
@Override
public void onResume() {
super.onResume();
if (getAdapter() != null) {
mAlbumListView.setAdapter(getAdapter());
if (state != null){
mAlbumListView.requestFocus();
mAlbumListView.onRestoreInstanceState(state);
}
}
}
That's enough
Old post but this is exactly what I needed, simple question, how to change it to count column rather than Row. Thankyou in advance. Novice to Excel.
=SUM(A1:INDIRECT(CONCATENATE("A",C5)))
I.e My data is A1 B1 C1 D1 etc rather then A1 A2 A3 A4.
Versioning your REST API is analogous to the versioning of any other API. Minor changes can be done in place, major changes might require a whole new API. The easiest for you is to start from scratch every time, which is when putting the version in the URL makes most sense. If you want to make life easier for the client you try to maintain backwards compatibility, which you can do with deprecation (permanent redirect), resources in several versions etc. This is more fiddly and requires more effort. But it's also what REST encourages in "Cool URIs don't change".
In the end it's just like any other API design. Weigh effort against client convenience. Consider adopting semantic versioning for your API, which makes it clear for your clients how backwards compatible your new version is.
I am using phpMyAdmin version 4.2.11. At the time of writing, my Status
tab looks like this (a few options expanded; note "Current settings", bottom right):
Note, there are no directly visible "features" that allow for the enabling of things such as slow_query_log
. So, I went digging on the internet because UI-oriented answers will only be relevant to a particular release and, therefore, will quickly become out of date. So, what do you do if you don't see a relevant answer, above?
As this article explains, you can run a global query to enable or disable the slow_query_log
et al. The queries for enabling and disabling these logs are not difficult, so don't be afraid of them, e.g.
SET GLOBAL slow_query_log = 'ON';
From here, phpMyAdmin is pretty helpful and a bit of Googling will get you up to speed in no time. For instance, after I ran the above query, I can go back to the "Instructions/Setup" option under the Status tab's Monitor
window and see this (note the further instructions):
You can also export the database and then use a program like notepad++ to replace words and then inmport aigain.
Google has threatened to remove apps from the Play Store if they use accessibility services for non-accessibility purposes. However, this is reportedly being reconsidered.
AccessibilityService
AccessibilityService
.onAccessibilityEvent
callback, check for the TYPE_WINDOW_STATE_CHANGED
event type to determine when the current window changes.PackageManager.getActivityInfo()
.GET_TASKS
permission.AccessibilityService
, they can't press the OK button if an app has placed an overlay on the screen. Some apps that do this are Velis Auto Brightness and Lux. This can be confusing because the user might not know why they can't press the button or how to work around it. AccessibilityService
won't know the current activity until the first change of activity.public class WindowChangeDetectingService extends AccessibilityService {
@Override
protected void onServiceConnected() {
super.onServiceConnected();
//Configure these here for compatibility with API 13 and below.
AccessibilityServiceInfo config = new AccessibilityServiceInfo();
config.eventTypes = AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED;
config.feedbackType = AccessibilityServiceInfo.FEEDBACK_GENERIC;
if (Build.VERSION.SDK_INT >= 16)
//Just in case this helps
config.flags = AccessibilityServiceInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS;
setServiceInfo(config);
}
@Override
public void onAccessibilityEvent(AccessibilityEvent event) {
if (event.getEventType() == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) {
if (event.getPackageName() != null && event.getClassName() != null) {
ComponentName componentName = new ComponentName(
event.getPackageName().toString(),
event.getClassName().toString()
);
ActivityInfo activityInfo = tryGetActivity(componentName);
boolean isActivity = activityInfo != null;
if (isActivity)
Log.i("CurrentActivity", componentName.flattenToShortString());
}
}
}
private ActivityInfo tryGetActivity(ComponentName componentName) {
try {
return getPackageManager().getActivityInfo(componentName, 0);
} catch (PackageManager.NameNotFoundException e) {
return null;
}
}
@Override
public void onInterrupt() {}
}
Merge this into your manifest:
<application>
<service
android:label="@string/accessibility_service_name"
android:name=".WindowChangeDetectingService"
android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE">
<intent-filter>
<action android:name="android.accessibilityservice.AccessibilityService"/>
</intent-filter>
<meta-data
android:name="android.accessibilityservice"
android:resource="@xml/accessibilityservice"/>
</service>
</application>
Put this in res/xml/accessibilityservice.xml
:
<?xml version="1.0" encoding="utf-8"?>
<!-- These options MUST be specified here in order for the events to be received on first
start in Android 4.1.1 -->
<accessibility-service
xmlns:tools="http://schemas.android.com/tools"
android:accessibilityEventTypes="typeWindowStateChanged"
android:accessibilityFeedbackType="feedbackGeneric"
android:accessibilityFlags="flagIncludeNotImportantViews"
android:description="@string/accessibility_service_description"
xmlns:android="http://schemas.android.com/apk/res/android"
tools:ignore="UnusedAttribute"/>
Each user of the app will need to explicitly enable the AccessibilityService
in order for it to be used. See this StackOverflow answer for how to do this.
Note that the user won't be able to press the OK button when trying to enable the accessibility service if an app has placed an overlay on the screen, such as Velis Auto Brightness or Lux.
The two types are distinct in JavaScript as well as TypeScript - TypeScript just gives us syntax to annotate and check types as we go along.
String
refers to an object instance that has String.prototype
in its prototype chain. You can get such an instance in various ways e.g. new String('foo')
and Object('foo')
. You can test for an instance of the String
type with the instanceof
operator, e.g. myString instanceof String
.
string
is one of JavaScript's primitive types, and string
values are primarily created with literals e.g. 'foo'
and "bar"
, and as the result type of various functions and operators. You can test for string
type using typeof myString === 'string'
.
The vast majority of the time, string
is the type you should be using - almost all API interfaces that take or return strings will use it. All JS primitive types will be wrapped (boxed) with their corresponding object types when using them as objects, e.g. accessing properties or calling methods. Since String
is currently declared as an interface rather than a class in TypeScript's core library, structural typing means that string
is considered a subtype of String
which is why your first line passes compilation type checks.
RxJS Operators are functions that build on the observables foundation to enable sophisticated manipulation of collections.
For example, RxJS defines operators such as map()
, filter()
, concat()
, and flatMap()
.
You can use pipes to link operators together. Pipes let you combine multiple functions into a single function.
The pipe()
function takes as its arguments the functions you want to combine, and returns a new function that, when executed, runs the composed functions in sequence.
I had the same problem and was solved by running the following in run
%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe -i
There is npm-package jsfiddle-downloader
.
This is what I've used:
::Date Variables - replace characters that are not legal as part of filesystem file names (to produce name like "backup_04.15.08.7z")
SET DT=%date%
SET DT=%DT:/=.%
SET DT=%DT:-=.%
If you want further ideas for automating backups to 7-Zip archives, I have a free/open project you can use or review for ideas: http://wittman.org/ziparcy/
Use the following query in sql tab:
SHOW CREATE TABLE your_table_name
Press GO button
After show table, above the table ( +options ) Hyperlink.
Press +options Hyperlink then appear some options select (Full texts) press GO button.
Show sql quaery.
try
netstat -a -t -n | grep 3306
to see any one listening to the 3306 port then kill it
I was having this problem for 2 days. Trying out the solutions posted on forums I accidentally ran into a situation where my log was getting this error
check that you do not already have another mysqld process
The code you have at the moment seems to be all right. Check what the checkboxes array contains using this. Add this code on the top of your php script and see whether the checkboxes are being passed to your script.
echo '<pre>'.print_r($_POST['myCheckboxes'], true).'</pre>';
exit;
SELECT *
INTO #Temp
FROM
(SELECT
Received,
Total,
Answer,
(CASE WHEN application LIKE '%STUFF%' THEN 'MORESTUFF' END) AS application
FROM
FirstTable
WHERE
Recieved = 1 AND
application = 'MORESTUFF'
GROUP BY
CASE WHEN application LIKE '%STUFF%' THEN 'MORESTUFF' END) data
WHERE
application LIKE
isNull(
'%MORESTUFF%',
'%')
I know this is an old question, but I wanted to share my approach. I use cURL as a proxy, very easy and consistent. Create a php page called submit.php, and add the following code:
<?
function post($url, $data) {
$header = array("User-Agent: " . $_SERVER["HTTP_USER_AGENT"], "Content-Type: application/x-www-form-urlencoded");
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
$response = curl_exec($curl);
curl_close($curl);
return $response;
}
$url = "your cross domain request here";
$data = $_SERVER["QUERY_STRING"];
echo(post($url, $data));
Then, in your js (jQuery here):
$.ajax({
type: 'POST',
url: 'submit.php',
crossDomain: true,
data: '{"some":"json"}',
dataType: 'json',
success: function(responseData, textStatus, jqXHR) {
var value = responseData.someKey;
},
error: function (responseData, textStatus, errorThrown) {
alert('POST failed.');
}
});
I also encountered a similar problem. I run Ubuntu 11.04 on VMware on a Windows 7 host OS. Virtual machines can't expose the physical wireless cards. All of that is using a virtualization layer.
try Integer.toString(integer value);
method as
ed = (EditText)findViewById(R.id.box);
int x = 10;
ed.setText(Integer.toString(x));
If in case you are using Python 3.x, you have to use
txt_entry = Entry(root)
txt_entry.pack()
txt_entry.delete(0, tkinter.END)
This should be (condition)? True statement : False statement
Leave out the "if"
A list
is immutable
by Default
, you can use ArrayList
instead. like this :
val orders = arrayListOf<String>()
then you can add/delete
items from this like below:
orders.add("Item 1")
orders.add("Item 2")
by default
ArrayList
ismutable
so you can perform the operations on it.
here's one i just wrote, maybe it's not as optimized (just uses a sorted dictionary) but simple to understand. you can insert objects of different kinds, so no generic queues.
using System;
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
namespace PrioQueue
{
public class PrioQueue
{
int total_size;
SortedDictionary<int, Queue> storage;
public PrioQueue ()
{
this.storage = new SortedDictionary<int, Queue> ();
this.total_size = 0;
}
public bool IsEmpty ()
{
return (total_size == 0);
}
public object Dequeue ()
{
if (IsEmpty ()) {
throw new Exception ("Please check that priorityQueue is not empty before dequeing");
} else
foreach (Queue q in storage.Values) {
// we use a sorted dictionary
if (q.Count > 0) {
total_size--;
return q.Dequeue ();
}
}
Debug.Assert(false,"not supposed to reach here. problem with changing total_size");
return null; // not supposed to reach here.
}
// same as above, except for peek.
public object Peek ()
{
if (IsEmpty ())
throw new Exception ("Please check that priorityQueue is not empty before peeking");
else
foreach (Queue q in storage.Values) {
if (q.Count > 0)
return q.Peek ();
}
Debug.Assert(false,"not supposed to reach here. problem with changing total_size");
return null; // not supposed to reach here.
}
public object Dequeue (int prio)
{
total_size--;
return storage[prio].Dequeue ();
}
public void Enqueue (object item, int prio)
{
if (!storage.ContainsKey (prio)) {
storage.Add (prio, new Queue ());
}
storage[prio].Enqueue (item);
total_size++;
}
}
}
The problem is that the default option of "yearRange" is 10 years.
So 2012 - 10 = 2002
.
So change the yearRange to c-20:c
or just 1999 (yearRange: '1999:c'
), and use that in combination with restrict dates (mindate, maxdate).
For more info: http://jqueryui.com/demos/datepicker/#option-yearRange
See example: http://jsfiddle.net/kGjdL/
And your code with the addition:
$(function () {
$('#datepicker').datepicker({
dateFormat: 'yy-mm-dd',
showButtonPanel: true,
changeMonth: true,
changeYear: true,
showOn: "button",
buttonImage: "images/calendar.gif",
buttonImageOnly: true,
minDate: new Date(1999, 10 - 1, 25),
maxDate: '+30Y',
yearRange: '1999:c',
inline: true
});
});
My workaround since none of the above appear to work in Chrome 63 and beyond
I fixed this on my site by replacing the offending input element with
<p class="input" contenteditable="true"> </p>
and using jQuery to populate a hidden field prior to submission.
But this is a truly awful hack made necessary by a bad decision at Chromium.
Objects are instances of classes. Classes are just the blueprints for objects. So given your class definition -
# Note the added (object) - this is the preferred way of creating new classes
class Student(object):
name = "Unknown name"
age = 0
major = "Unknown major"
You can create a make_student
function by explicitly assigning the attributes to a new instance of Student
-
def make_student(name, age, major):
student = Student()
student.name = name
student.age = age
student.major = major
return student
But it probably makes more sense to do this in a constructor (__init__
) -
class Student(object):
def __init__(self, name="Unknown name", age=0, major="Unknown major"):
self.name = name
self.age = age
self.major = major
The constructor is called when you use Student()
. It will take the arguments defined in the __init__
method. The constructor signature would now essentially be Student(name, age, major)
.
If you use that, then a make_student
function is trivial (and superfluous) -
def make_student(name, age, major):
return Student(name, age, major)
For fun, here is an example of how to create a make_student
function without defining a class. Please do not try this at home.
def make_student(name, age, major):
return type('Student', (object,),
{'name': name, 'age': age, 'major': major})()
use js to prevent add data:
if ( window.history.replaceState ) {
window.history.replaceState( null, null, window.location.href );
}
Regex.Replace(htmlText, "<.*?>", string.Empty);
Try to use a loop, let
, and printf
for the padding:
a=1
for i in *.jpg; do
new=$(printf "%04d.jpg" "$a") #04 pad to length of 4
mv -i -- "$i" "$new"
let a=a+1
done
using the -i
flag prevents automatically overwriting existing files.
Maybe someone else can explain the reasons behind your problem but you can solve it by specifying the height of the container and then setting the height of the image to be 100%. It is important that the width
of the image appears before the height
.
<html>
<head>
<style>
.container {
background: blue;
padding: 10px;
height: 100%;
max-height: 200px;
max-width: 300px;
}
.container img {
width: 100%;
height: 100%
}
</style>
</head>
<body>
<div class="container">
<img src="http://placekitten.com/400/500" />
</div>
</body>
</html>
You can use webpack to provide it. It will be then injected DOM automatically.
module.exports = {
context: process.cwd(),
entry: {
something: [
path.join(root, 'src/something.ts')
],
vendor: ['jquery']
},
devtool: 'source-map',
output: {
path: path.join(root, '/dist/js'),
sourceMapFilename: "[name].js.map",
filename: '[name].js'
},
module: {
rules: [
{test: /\.ts$/, exclude: /node_modules/, loader: 'ts-loader'}
]
},
resolve: {
extensions: ['.ts', '.es6', '.js', '.json']
},
plugins: [
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery'
}),
]
};
I use char 'f', 'm' and 'u' because I surmise the gender from name, voice and conversation, and sometimes don't know the gender. The final determination is their opinion.
It really depends how well you know the person and whether your criteria is physical form or personal identity. A psychologist might need additional options - cross to female, cross to male, trans to female, trans to male, hermaphrodite and undecided. With 9 options, not clearly defined by a single character, I might go with Hugo's advice of tiny integer.
This is easy. Just add mute=1 to the src parameter of iframe.
Example:
<iframe src="https://www.youtube.com/embed/uNRGWVJ10gQ?controls=0&mute=1&showinfo=0&rel=0&autoplay=1&loop=1&playlist=uNRGWVJ10gQ" frameborder="0" allowfullscreen></iframe>
I was trying to run a .net core 3.1 site from IIS 10 on windows 10 pro box, and got this error. Did the following to resolve it.
First turn on the following iis feature on.
Then follow the link below.
Install the .net core hosting bundle.
The direct link is
I have installed the .net core sdk and run time as well. But this did not resolve the issue.
What made the difference is the .net core hosting bundle.
You can use T-Regx library, that doesn't need delimiters
pattern('^([0-9]+)$')->match($input);
In my case i had to load images on radio button click,
I just uses the regular onclick
event and it worked for me.
<input type="radio" name="colors" value="{{color.id}}" id="{{color.id}}-option" class="color_radion" onclick="return get_images(this, {{color.id}})">
<script>
function get_images(obj, color){
console.log($("input[type='radio'][name='colors']:checked").val());
}
</script>
def function(arg)->123:
It's simply a return type, integer in this case doesn't matter which number you write.
like Java :
public int function(int args){...}
But for Python (how Jim Fasarakis Hilliard said) the return type it's just an hint, so it's suggest the return but allow anyway to return other type like a string..
I ran into this recently. Our organization restricts the accounts that run application pools to a select list of servers in Active Directory. I found that I had not added one of the machines hosting the application to the "Log On To" list for the account in AD.
You can use use findFragmentById
in FragmentManager
.
Since you are using the Support library (you are extending FragmentActivity) you can use:
getSupportFragmentManager().findFragmentById(R.id.pageview)
If you are not using the support library (so you are on Honeycomb+ and you don't want to use the support library):
getFragmentManager().findFragmentById(R.id.pageview)
Please consider that using the support library is recommended even on Honeycomb+.
The statement from Microsoft regarding the end of Internet Explorer 11 support mentions that it will continue to receive security updates, compatibility fixes, and technical support until its end of life. The wording of this statement leads me to believe that Microsoft has no plans to continue adding features to Internet Explorer 11, and instead will be focusing on Edge.
If you require ES6 features in Internet Explorer 11, check out a transpiler such as Babel.
Are you sure that all the lines have at least 2 columns? Can you try something like, just to check?:
sc.textFile("file.csv") \
.map(lambda line: line.split(",")) \
.filter(lambda line: len(line)>1) \
.map(lambda line: (line[0],line[1])) \
.collect()
Alternatively, you could print the culprit (if any):
sc.textFile("file.csv") \
.map(lambda line: line.split(",")) \
.filter(lambda line: len(line)<=1) \
.collect()
Muhammad Musavi's comment is the best answer, so here it is surfaced as an actual Answer:
thead/tfoot
are automatically repeated on the top and bottom of each page. However, tfoot isn't sticky to the bottom of the last page.
position: fixed
in print will repeat on each page, and the footer will stick to the bottom of all pages including the last one - but, it won't create space for its contents.
Combine them:
HTML:
<header>(repeated header)</header>
<table class=paging><thead><tr><td> </td></tr></thead><tbody><tr><td>
(content goes here)
</td></tr></tbody><tfoot><tr><td> </td></tr></tfoot></table>
<footer>(repeated footer)</footer>
CSS:
@page {
size: letter;
margin: .5in;
}
@media print {
table.paging thead td, table.paging tfoot td {
height: .5in;
}
}
header, footer {
width: 100%; height: .5in;
}
header {
position: absolute;
top: 0;
}
@media print {
header, footer {
position: fixed;
}
footer {
bottom: 0;
}
}
There are a lot of niceties you can add in here, but I've intentionally slashed this to the bare minimum to get a cleanly rendering header and footer, appearing once on-screen and at the top and bottom of every printed page.
https://medium.com/@Idan_Co/the-ultimate-print-html-template-with-header-footer-568f415f6d2a
There are a number of different solutions for finding running median from streamed data, I will briefly talk about them at the very end of the answer.
The question is about the details of the a specific solution (max heap/min heap solution), and how heap based solution works is explained below:
For the first two elements add smaller one to the maxHeap on the left, and bigger one to the minHeap on the right. Then process stream data one by one,
Step 1: Add next item to one of the heaps
if next item is smaller than maxHeap root add it to maxHeap,
else add it to minHeap
Step 2: Balance the heaps (after this step heaps will be either balanced or
one of them will contain 1 more item)
if number of elements in one of the heaps is greater than the other by
more than 1, remove the root element from the one containing more elements and
add to the other one
Then at any given time you can calculate median like this:
If the heaps contain equal amount of elements;
median = (root of maxHeap + root of minHeap)/2
Else
median = root of the heap with more elements
Now I will talk about the problem in general as promised in the beginning of the answer. Finding running median from a stream of data is a tough problem, and finding an exact solution with memory constraints efficiently is probably impossible for the general case. On the other hand, if the data has some characteristics we can exploit, we can develop efficient specialized solutions. For example, if we know that the data is an integral type, then we can use counting sort, which can give you a constant memory constant time algorithm. Heap based solution is a more general solution because it can be used for other data types (doubles) as well. And finally, if the exact median is not required and an approximation is enough, you can just try to estimate a probability density function for the data and estimate median using that.
Hope it might help someone instantly.
In Python 2.7: By default, division operator will return integer output.
to get the result in double multiple 1.0 to "dividend or divisor"
100/35 => 2 #(Expected is 2.857142857142857)
(100*1.0)/35 => 2.857142857142857
100/(35*1.0) => 2.857142857142857
In Python 3
// => used for integer output
/ => used for double output
100/35 => 2.857142857142857
100//35 => 2
100.//35 => 2.0 # floating-point result if divsor or dividend real
The Authenticity Token is a countermeasure to Cross-Site Request Forgery (CSRF). What is CSRF, you ask?
It's a way that an attacker can potentially hijack sessions without even knowing session tokens.
Scenario:
CSRF solution:
A slightly more robust method I needed to use recently:
- (void) dismissKeyboard {
NSArray *windows = [UIApplication sharedApplication].windows;
for(UIWindow *window in windows) [window endEditing:true];
// Or if you're only working with one UIWindow:
[[UIApplication sharedApplication].keyWindow endEditing:true];
}
I found some of the other "global" methods didn't work (for example, UIWebView
& WKWebView
refused to resign).
If your software uses a ProxySelector
(for example for using a PAC-script instead of a static host/port) and your HTTPComponents is version 4.3 or above then you can use your ProxySelector
for your HttpClient
like this:
ProxySelector myProxySelector = ...;
HttpClient myHttpClient = HttpClientBuilder.create().setRoutePlanner(new SystemDefaultRoutePlanner(myProxySelector))).build();
And then do your requests as usual:
HttpGet myRequest = new HttpGet("/");
myHttpClient.execute(myRequest);
To count specified words only like John, John99, John_John and John's only. Change regex according to yourself and count the specified words only.
public static int wordCount(String content) {
int count = 0;
String regex = "([a-zA-Z_’][0-9]*)+[\\s]*";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(content);
while(matcher.find()) {
count++;
System.out.println(matcher.group().trim()); //If want to display the matched words
}
return count;
}
if not x is None
is more similar to other programming languages, but if x is not None
definitely sounds more clear (and is more grammatically correct in English) to me.
That said it seems like it's more of a preference thing to me.
The easiest way is:
onClick= 'location.href="/controller/action/"+paramterValue'
Basically , For example :
public class Kerem
{
public static void main(String[] args)
{
short x = 10;
short y = 3;
Object o = y;
System.out.println(o.getClass()); // java.lang.Short
}
}
You have to specify the folder where you are saving it and it has to exist, in other case it will throw an error.
var s = txt.CreateTextFile("c:\\11.txt", true);
I needed to connect to remote Amazon server
ssh -i ~/.ssh/test.pem -fN -L 5555:localhost:5678 [email protected]
I was getting the following error.
ssh: Could not resolve hostname <hostname.com>: nodename nor servname provided, or not known
Pinging the host resolved the issue. I am using Mac OSX Seirra.
ping hostname.com
Now problem resolved. Able to connect to the server.
Note: I tried this solution also. But it didn't work out. Then ping
resolved the issue.
Not quite...
http://en.wikipedia.org/wiki/Representational_State_Transfer
REST was initially described in the context of HTTP, but is not limited to that protocol. RESTful architectures can be based on other Application Layer protocols if they already provide a rich and uniform vocabulary for applications based on the transfer of meaningful representational state. RESTful applications maximise the use of the pre-existing, well-defined interface and other built-in capabilities provided by the chosen network protocol, and minimise the addition of new application-specific features on top of it.
http://www.looselycoupled.com/glossary/SOAP
(Simple Object Access Protocol) The standard for web services messages. Based on XML, SOAP defines an envelope format and various rules for describing its contents. Seen (with WSDL and UDDI) as one of the three foundation standards of web services, it is the preferred protocol for exchanging web services, but by no means the only one; proponents of REST say that it adds unnecessary complexity.
Guessing at all the things omitted from the original question, but, assuming Python 2.x the key is to read the error messages carefully: in particular where you call 'encode' but the message says 'decode' and vice versa, but also the types of the values included in the messages.
In the first example string
is of type unicode
and you attempted to decode it which is an operation converting a byte string to unicode. Python helpfully attempted to convert the unicode value to str
using the default 'ascii' encoding but since your string contained a non-ascii character you got the error which says that Python was unable to encode a unicode value. Here's an example which shows the type of the input string:
>>> u"\xa0".decode("ascii", "ignore")
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
u"\xa0".decode("ascii", "ignore")
UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 0: ordinal not in range(128)
In the second case you do the reverse attempting to encode a byte string. Encoding is an operation that converts unicode to a byte string so Python helpfully attempts to convert your byte string to unicode first and, since you didn't give it an ascii string the default ascii decoder fails:
>>> "\xc2".encode("ascii", "ignore")
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
"\xc2".encode("ascii", "ignore")
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 0: ordinal not in range(128)
mongorestore -d db_name /path/
make sure you run this query in bin folder of mongoDb
C:\Program Files\MongoDB\Server\4.2\bin -
then run this above command.
I have been playing around flexbox lately and i came to solution for this through experimentation and the following reasoning. However, in reality I'm not sure if this is exactly what happens.
If real width is affected by flex system. So after width of elements hit max width of parent they extra width set in css is ignored. Then it's safe to set width to 100%.
Since height of img tag is derived from image itself then setting height to 0% could do something. (this is where i am unclear as to what...but it made sense to me that it should fix it)
(remember saw it here first!)
.slider {
display: flex;
}
.slider img {
height: 0%;
width: 100%;
margin: 0 5px;
}
Works only in chrome yet
I created an extension method to the ObservableCollection
public static void MySort<TSource,TKey>(this ObservableCollection<TSource> observableCollection, Func<TSource, TKey> keySelector)
{
var a = observableCollection.OrderBy(keySelector).ToList();
observableCollection.Clear();
foreach(var b in a)
{
observableCollection.Add(b);
}
}
It seems to work and you don't need to implement IComparable
HTTP 1.1 is the latest version of Hypertext Transfer Protocol, the World Wide Web application protocol that runs on top of the Internet's TCP/IP suite of protocols. compare to HTTP 1.0 , HTTP 1.1 provides faster delivery of Web pages than the original HTTP and reduces Web traffic.
Web traffic Example: For example, if you are accessing a server. At the same time so many users are accessing the server for the data, Then there is a chance for hanging the Server. This is Web traffic.
SQL Developer Version 4.1.0.19
Step 1: Go to Tools -> Preferences
Step 2: Select Database -> NLS
Step 3: Go to Date Format and Enter DD-MON-RR HH24: MI: SS
Step 4: Click OK.
See the above definition where it states that a callback function is passed off to some other function and at some point it is called.
In C++ it is desirable to have callback functions call a classes method. When you do this you have access to the member data. If you use the C way of defining a callback you will have to point it to a static member function. This is not very desirable.
Here is how you can use callbacks in C++. Assume 4 files. A pair of .CPP/.H files for each class. Class C1 is the class with a method we want to callback. C2 calls back to C1's method. In this example the callback function takes 1 parameter which I added for the readers sake. The example doesn't show any objects being instantiated and used. One use case for this implementation is when you have one class that reads and stores data into temporary space and another that post processes the data. With a callback function, for every row of data read the callback can then process it. This technique cuts outs the overhead of the temporary space required. It is particularly useful for SQL queries that return a large amount of data which then has to be post-processed.
/////////////////////////////////////////////////////////////////////
// C1 H file
class C1
{
public:
C1() {};
~C1() {};
void CALLBACK F1(int i);
};
/////////////////////////////////////////////////////////////////////
// C1 CPP file
void CALLBACK C1::F1(int i)
{
// Do stuff with C1, its methods and data, and even do stuff with the passed in parameter
}
/////////////////////////////////////////////////////////////////////
// C2 H File
class C1; // Forward declaration
class C2
{
typedef void (CALLBACK C1::* pfnCallBack)(int i);
public:
C2() {};
~C2() {};
void Fn(C1 * pThat,pfnCallBack pFn);
};
/////////////////////////////////////////////////////////////////////
// C2 CPP File
void C2::Fn(C1 * pThat,pfnCallBack pFn)
{
// Call a non-static method in C1
int i = 1;
(pThat->*pFn)(i);
}
In cases where one is using android:layout_weight
property to assign available screen space to layout components, for instance
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<LinearLayout
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="match_parent"
android:orientation="vertical">
...
...
</LinearLayout>
/* And we want to add a verical separator here */
<LinearLayout
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="match_parent"
android:orientation="vertical">
...
...
</LinearLayout>
</LinearLayout>
To add a separator between the existing two layouts which has taken the entire screen space already, we cannot just add another LinearLayout with android:weight:"1"
because that will make three equal width columns which we don't want. Instead, we will decrease the amount of space we will be giving to this new layout.
Final code would look like this:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<LinearLayout
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="match_parent"
android:orientation="vertical">
...
...
</LinearLayout>
/* *************** ********************** */
/* Add another LinearLayout with android:layout_weight="0.01" and
android:background="#your_choice" */
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="0.01"
android:background="@android:color/darker_gray"
/>
/* Or View can be used */
<View
android:layout_width="1dp"
android:layout_height="match_parent"
android:layout_marginTop="16dp"
android:background="@android:color/darker_gray"
/>
/* *************** ********************** */
<LinearLayout
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="match_parent"
android:orientation="vertical">
...
...
</LinearLayout>
</LinearLayout>
header("Content-Type: text/html; charset=utf8");
$url = simplexml_load_file("http://URI.com");
foreach ($url->PRODUCT as $product) {
foreach($urun->attributes() as $k => $v) {
echo $k." : ".$v.' <br />';
}
echo '<hr/>';
}
If you want to get the date when the user selects it, you can do this:
$("#datepicker").datepicker({
onSelect: function() {
var dateObject = $(this).datepicker('getDate');
}
});
I am not sure about the second part of your question. But, have you tried using style sheets and relative positioning?
I got yet another alternative for the solutions offered by runeks and todotresde that also avoids the pitfalls discussed in the comments to Spudley's answer:
try {
console.log(message);
} catch (e) {
}
It's a bit scruffy but on the other hand it's concise and covers all the logging methods covered in runeks' answer and it has the huge advantage that you can open the console window of IE at any time and the logs come flowing in.
NSDictionary -> NSData:
NSData *myData = [NSKeyedArchiver archivedDataWithRootObject:myDictionary];
NSData -> NSDictionary:
NSDictionary *myDictionary = (NSDictionary*) [NSKeyedUnarchiver unarchiveObjectWithData:myData];
You can try
#include <iostream>
#include <conio.h>
int main() {
//some codes
getch();
return 0;
}
To achieve it, you have to modify the background-color
of the element.
Ways to create a (semi-) transparent color:
The CSS color name transparent
creates a completely transparent color.
Usage:
.transparent{
background-color: transparent;
}
Using rgba
or hsla
color functions, that allow you to add the alpha channel (opacity) to the rgb
and hsl
functions. Their alpha values range from 0 - 1.
Usage:
.semi-transparent-yellow{
background-color: rgba(255, 255, 0, 0.5);
}
.transparent{
background-color: hsla(0, 0%, 0%, 0);
}
Besides the already mentioned solutions, you can also use the HEX format with alpha value (#RRGGBBAA
or #RGBA
notation).
That's pretty new (contained by CSS Color Module Level 4), but already implemented in larger browsers (sorry, no IE).
This differs from the other solutions, as this treats the alpha channel (opacity) as a hexadecimal value as well, making it range from 0 - 255 (FF
).
Usage:
.semi-transparent-yellow{
background-color: #FFFF0080;
}
.transparent{
background-color: #0000;
}
You can try them out as well:
transparent
:div {
position: absolute;
top: 50px;
left: 100px;
height: 100px;
width: 200px;
text-align: center;
line-height: 100px;
border: 1px dashed grey;
background-color: transparent;
}
_x000D_
<img src="https://via.placeholder.com/200x100">
<div>
Using `transparent`
</div>
_x000D_
rgba()
:div {
position: absolute;
top: 50px;
left: 100px;
height: 100px;
width: 200px;
text-align: center;
line-height: 100px;
border: 1px dashed grey;
background-color: rgba(0, 255, 0, 0.3);
}
_x000D_
<img src="https://via.placeholder.com/200x100">
<div>
Using `rgba()`
</div>
_x000D_
#RRGGBBAA
:div {
position: absolute;
top: 50px;
left: 100px;
height: 100px;
width: 200px;
text-align: center;
line-height: 100px;
border: 1px dashed grey;
background-color: #FF000060
}
_x000D_
<img src="https://via.placeholder.com/200x100">
<div>
Using `#RRGGBBAA`
</div>
_x000D_
To start server locally paste the below code in package.json and run npm start in command line.
"scripts": {
"start": "http-server -c-1 -p 8081"
},
Not able to understand your actual problem but your case statement is incorrect
CASE
WHEN
TABLE3.COL3 IS NULL
THEN TABLE2.COL3
ELSE
TABLE3.COL3
END
AS
COL4
Email headers don't matter to the smtp server. Just add the CC and BCC recipients to the toaddrs when you send your email. For CC, add them to the CC header.
toaddr = '[email protected]'
cc = ['[email protected]','[email protected]']
bcc = ['[email protected]']
fromaddr = '[email protected]'
message_subject = "disturbance in sector 7"
message_text = "Three are dead in an attack in the sewers below sector 7."
message = "From: %s\r\n" % fromaddr
+ "To: %s\r\n" % toaddr
+ "CC: %s\r\n" % ",".join(cc)
+ "Subject: %s\r\n" % message_subject
+ "\r\n"
+ message_text
toaddrs = [toaddr] + cc + bcc
server = smtplib.SMTP('smtp.sunnydale.k12.ca.us')
server.set_debuglevel(1)
server.sendmail(fromaddr, toaddrs, message)
server.quit()
Although this is a old post, I have spent 3 hours to fix my issue and I think this might help someone in future.
Here is my jquery-dialog
hack to show html content inside an <iframe>
:
let modalProperties = {autoOpen: true, width: 900, height: 600, modal: true, title: 'Modal Title'};
let modalHtmlContent = '<div>My Content First div</div><div>My Content Second div</div>';
// create wrapper iframe
let wrapperIframe = $('<iframe src="" frameborder="0" style="width:100%; height:100%;"></iframe>');
// create jquery dialog by a 'div' with 'iframe' appended
$("<div></div>").append(wrapperIframe).dialog(modalProperties);
// insert html content to iframe 'body'
let wrapperIframeDocument = wrapperIframe[0].contentDocument;
let wrapperIframeBody = $('body', wrapperIframeDocument);
wrapperIframeBody.html(modalHtmlContent);
You'll need to use DrawEllipse if you want to draw a circle using GDI+.
An example is here: http://www.websupergoo.com/helpig6net/source/3-examples/9-drawgdi.htm
It's netstat -ano|findstr port no
Result would show process id in last column
for the people who face the same problem in Windows - 10 please follow the below instructions,
https://github.com/Microsoft/vscode/issues/21957
It might be the case that, C:\Program Files (x86)\Microsoft VS Code\bin is missing in environment variables., kindly look into the following image for the solution, https://cloud.githubusercontent.com/assets/4076309/23575794/61d7cc2a-00b9-11e7-843b-bcd6f00f595f.png
result = M.A1
https://docs.scipy.org/doc/numpy-1.14.0/reference/generated/numpy.matrix.A1.html
matrix.A1
1-d base array
install these two packages
npm i --save-dev react-app-rewired customize-cra
package.json
"scripts": {
- "start": "react-scripts start"
+ "start": "react-app-rewired start"
},
config-overrides.js
const { removeModuleScopePlugin } = require('customize-cra');
module.exports = function override(config, env) {
if (!config.plugins) {
config.plugins = [];
}
removeModuleScopePlugin()(config);
return config;
};
This is incredibly old, but I stumbled across it trying to find an answer to a different question.
my question is how do you get the values from both map keys in the arraylist?
for (String key : map.keyset()) {
list.add(key + "|" + map.get(key));
}
the Map size always return a value of 2, which is just the elements
I think you may be confused by the functionality of HashMap
. HashMap
only allows 1 to 1 relationships in the map.
For example if you have:
String TAG_FOO = "FOO";
String TAG_BAR = "BAR";
and attempt to do something like this:
ArrayList<String> bars = ArrayList<>("bar","Bar","bAr","baR");
HashMap<String,String> map = new HashMap<>();
for (String bar : bars) {
map.put(TAG_BAR, bar);
}
This code will end up setting the key entry "BAR"
to be associated with the final item in the list bars
.
In your example you seem to be confused that there are only two items, yet you only have two keys recorded which leads me to believe that you've simply overwritten the each key's field multiple times.
>>> keyDict = {"a","b","c","d"}
>>> dict([(key, []) for key in keyDict])
Output:
{'a': [], 'c': [], 'b': [], 'd': []}
This works well in ASP.NET webforms.
Change the script to
<img src="' + imagePath + 'chevron-large-right-grey.gif" alt="'.....
I have a master page for each directory level and this is in the Page_Init event
Dim vPath As String = ResolveUrl("~/Images/")
Dim SB As New StringBuilder
SB.Append("var imagePath = '" & vPath & "'; ")
ScriptManager.RegisterClientScriptBlock(Me, Me.GetType(), "LoadImagePath", SB.ToString, True)
Now regardless of whether the application is run locally or deployed you get the correct full path
http://localhost:57387/Images/chevron-large-left-blue.png
In my case, Environment.NewLine was working fine while previewing the report in Visual Studio. But when I tried to publish the rdl to Dynamics 365 CE, I received the error "The report server has RDLSandboxing enabled and the Value expression for the text box 'Textbox10' contains a reference to a type, namespace, or member 'Environment' that is not allowed."
So I had to replace Environment.NewLine with vbcrlf.
if you want to get the first N elements and also remove it from the array, you can use array_splice()
(note the 'p' in "splice"):
http://docs.php.net/manual/da/function.array-splice.php
use it like so: $array_without_n_elements = array_splice($old_array, 0, N)
In additon to directly accessing the array, there is also
array_push
— Push one or more elements onto the end of array
If you're getting this error and you are using Maven to build your Jars, then there is a good chance that you simply do not have your Java classes in src/main/java/
.
In my case I created my project in Eclipse which defaults to src
(rather than src/main/java/
.
So I ended up with something like mypackage.morepackage.myclass
and a directory structure looking like src/mypackage/morepackage/myclass
, which inherently has nothing wrong. But when you run mvn clean install
it will look for src/main/java/mypackage/morepackage/myclass
. It will not find the class but it won't error either. So it will successfully build and you when you run your outputted Jar the result is:
Error: Could not find or load main class mypackage.morepackage.myclass
Because it simply never included your class in the packaged Jar.
In the server in .NET 4.0 in web.config you also need to change in the default binding. Set the follwowing 3 parms:
< basicHttpBinding>
< !--http://www.intertech.com/Blog/post/NET-40-WCF-Default-Bindings.aspx
- Enable transfer of large strings with maxBufferSize, maxReceivedMessageSize and maxStringContentLength
-->
< binding **maxBufferSize="2147483647" maxReceivedMessageSize="2147483647"**>
< readerQuotas **maxStringContentLength="2147483647"**/>
< /binding>
This question shows precisely why I like to do things the way I mentioned in my question is const after type id acceptable?
In short, I find the easiest way to remember the rule is that the "const" goes after the thing it applies to. So in your question, "int const *" means that the int is constant, while "int * const" would mean that the pointer is constant.
If someone decides to put it at the very front (eg: "const int *"), as a special exception in that case it applies to the thing after it.
Many people like to use that special exception because they think it looks nicer. I dislike it, because it is an exception, and thus confuses things.
This cannot be done with pure HTML. You must rely on JavaScript for this trick.
However, if you place two forms on the HTML page you can do this.
Form1 would have the previous button.
Form2 would have any user inputs + the next button.
When the user presses Enter in Form2, the Next submit button would fire.
This is how I used this is as an example:
CAST(vAvgMaterialUnitCost.`avgUnitCost` AS DECIMAL(11,2)) * woMaterials.`qtyUsed` AS materialCost
FYI this kind of code works (you can find it ugly, it is your right :) ) :
def list = null
list.each { println it }
soSomething()
In other words, this code has null/empty checks both useless:
if (members && !members.empty) {
members.each { doAnotherThing it }
}
def doAnotherThing(def member) {
// Some work
}
Place this meta tag after head tag
<meta http-equiv="x-ua-compatible" content="IE=edge">
For replace you can use vbCrLf
:
Replace(string, vbCrLf, "")
You can also use chr(13)+chr(10)
.
I seem to remember in some odd cases that chr(10)
comes before chr(13)
.
I found the solution here:
How to properly -filter multiple strings in a PowerShell copy script
You have to use -Include
flag for Get-ChildItem
My Example:
$Location = "C:\user\files"
$result = (Get-ChildItem $Location\* -Include *.png, *.gif, *.jpg)
Dont forget put "*" after path location.
This error will also appear if you try to connect to an exposed port from within a Docker container, when nothing is actively serving the port.
On a host where nothing is listening/bound to that port you'd get a No connection could be made because the target machine actively refused it
error instead when making a request to a local URL that is not served, eg: localhost:5000
. However, if you start a container that binds to the port, but there is no server running inside of it actually serving the port, any requests to that port on localhost will result in:
[Errno 99] Cannot assign requested address
(if called from within the container), or[Errno 0] Error
(if called from outside of the container).You can reproduce this error and the behaviour described above as follows:
Start a dummy container (note: this will pull the python image if not found locally):
docker run --name serv1 -p 5000:5000 -dit python
Then for [Errno 0] Error
enter a Python console on host, while for [Errno 99] Cannot assign requested address
access a Python console on the container by calling:
docker exec -it -u 0 serv1 python
And then in either case call:
import urllib.request
urllib.request.urlopen('https://localhost:5000')
I concluded with treating either of these errors as equivalent to No connection could be made because the target machine actively refused it
rather than trying to fix their cause - although please advise if that's a bad idea.
I've spent over a day figuring this one out, given that all resources and answers I could find on the [Errno 99] Cannot assign requested address
point in the direction of binding to an occupied port, connecting to an invalid IP, sysctl
conflicts, docker network issues, TIME_WAIT
being incorrect, and many more things. Therefore I wanted to leave this answer here, despite not being a direct answer to the question at hand, given that it can be a common cause for the error described in this question.
You are right, there is no datatype in SQL-Server which can hold a list of integers. But what you can do is store a list of integers as a string.
DECLARE @listOfIDs varchar(8000);
SET @listOfIDs = '1,2,3,4';
You can then split the string into separate integer values and put them into a table. Your procedure might already do this.
You can also use a dynamic query to achieve the same outcome:
DECLARE @SQL nvarchar(8000);
SET @SQL = 'SELECT * FROM TabA WHERE TabA.ID IN (' + @listOfIDs + ')';
EXECUTE (@SQL);
Find the <SHA#>
for the commit you want to go. You can find it in github or by typing git log
or git reflog show
at the command line and then do
git reset --hard <SHA#>
Basically, eval
is used to evaluate a single dynamically generated Python expression, and exec
is used to execute dynamically generated Python code only for its side effects.
eval
and exec
have these two differences:
eval
accepts only a single expression, exec
can take a code block that has Python statements: loops, try: except:
, class
and function/method def
initions and so on.
An expression in Python is whatever you can have as the value in a variable assignment:
a_variable = (anything you can put within these parentheses is an expression)
eval
returns the value of the given expression, whereas exec
ignores the return value from its code, and always returns None
(in Python 2 it is a statement and cannot be used as an expression, so it really does not return anything).
In versions 1.0 - 2.7, exec
was a statement, because CPython needed to produce a different kind of code object for functions that used exec
for its side effects inside the function.
In Python 3, exec
is a function; its use has no effect on the compiled bytecode of the function where it is used.
Thus basically:
>>> a = 5
>>> eval('37 + a') # it is an expression
42
>>> exec('37 + a') # it is an expression statement; value is ignored (None is returned)
>>> exec('a = 47') # modify a global variable as a side effect
>>> a
47
>>> eval('a = 47') # you cannot evaluate a statement
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1
a = 47
^
SyntaxError: invalid syntax
The compile
in 'exec'
mode compiles any number of statements into a bytecode that implicitly always returns None
, whereas in 'eval'
mode it compiles a single expression into bytecode that returns the value of that expression.
>>> eval(compile('42', '<string>', 'exec')) # code returns None
>>> eval(compile('42', '<string>', 'eval')) # code returns 42
42
>>> exec(compile('42', '<string>', 'eval')) # code returns 42,
>>> # but ignored by exec
In the 'eval'
mode (and thus with the eval
function if a string is passed in), the compile
raises an exception if the source code contains statements or anything else beyond a single expression:
>>> compile('for i in range(3): print(i)', '<string>', 'eval')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1
for i in range(3): print(i)
^
SyntaxError: invalid syntax
Actually the statement "eval accepts only a single expression" applies only when a string (which contains Python source code) is passed to eval
. Then it is internally compiled to bytecode using compile(source, '<string>', 'eval')
This is where the difference really comes from.
If a code
object (which contains Python bytecode) is passed to exec
or eval
, they behave identically, excepting for the fact that exec
ignores the return value, still returning None
always. So it is possible use eval
to execute something that has statements, if you just compile
d it into bytecode before instead of passing it as a string:
>>> eval(compile('if 1: print("Hello")', '<string>', 'exec'))
Hello
>>>
works without problems, even though the compiled code contains statements. It still returns None
, because that is the return value of the code object returned from compile
.
In the 'eval'
mode (and thus with the eval
function if a string is passed in), the compile
raises an exception if the source code contains statements or anything else beyond a single expression:
>>> compile('for i in range(3): print(i)', '<string>'. 'eval')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1
for i in range(3): print(i)
^
SyntaxError: invalid syntax
exec
and eval
The exec
function (which was a statement in Python 2) is used for executing a dynamically created statement or program:
>>> program = '''
for i in range(3):
print("Python is cool")
'''
>>> exec(program)
Python is cool
Python is cool
Python is cool
>>>
The eval
function does the same for a single expression, and returns the value of the expression:
>>> a = 2
>>> my_calculation = '42 * a'
>>> result = eval(my_calculation)
>>> result
84
exec
and eval
both accept the program/expression to be run either as a str
, unicode
or bytes
object containing source code, or as a code
object which contains Python bytecode.
If a str
/unicode
/bytes
containing source code was passed to exec
, it behaves equivalently to:
exec(compile(source, '<string>', 'exec'))
and eval
similarly behaves equivalent to:
eval(compile(source, '<string>', 'eval'))
Since all expressions can be used as statements in Python (these are called the Expr
nodes in the Python abstract grammar; the opposite is not true), you can always use exec
if you do not need the return value. That is to say, you can use either eval('my_func(42)')
or exec('my_func(42)')
, the difference being that eval
returns the value returned by my_func
, and exec
discards it:
>>> def my_func(arg):
... print("Called with %d" % arg)
... return arg * 2
...
>>> exec('my_func(42)')
Called with 42
>>> eval('my_func(42)')
Called with 42
84
>>>
Of the 2, only exec
accepts source code that contains statements, like def
, for
, while
, import
, or class
, the assignment statement (a.k.a a = 42
), or entire programs:
>>> exec('for i in range(3): print(i)')
0
1
2
>>> eval('for i in range(3): print(i)')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1
for i in range(3): print(i)
^
SyntaxError: invalid syntax
Both exec
and eval
accept 2 additional positional arguments - globals
and locals
- which are the global and local variable scopes that the code sees. These default to the globals()
and locals()
within the scope that called exec
or eval
, but any dictionary can be used for globals
and any mapping
for locals
(including dict
of course). These can be used not only to restrict/modify the variables that the code sees, but are often also used for capturing the variables that the exec
uted code creates:
>>> g = dict()
>>> l = dict()
>>> exec('global a; a, b = 123, 42', g, l)
>>> g['a']
123
>>> l
{'b': 42}
(If you display the value of the entire g
, it would be much longer, because exec
and eval
add the built-ins module as __builtins__
to the globals automatically if it is missing).
In Python 2, the official syntax for the exec
statement is actually exec code in globals, locals
, as in
>>> exec 'global a; a, b = 123, 42' in g, l
However the alternate syntax exec(code, globals, locals)
has always been accepted too (see below).
compile
The compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)
built-in can be used to speed up repeated invocations of the same code with exec
or eval
by compiling the source into a code
object beforehand. The mode
parameter controls the kind of code fragment the compile
function accepts and the kind of bytecode it produces. The choices are 'eval'
, 'exec'
and 'single'
:
'eval'
mode expects a single expression, and will produce bytecode that when run will return the value of that expression:
>>> dis.dis(compile('a + b', '<string>', 'eval'))
1 0 LOAD_NAME 0 (a)
3 LOAD_NAME 1 (b)
6 BINARY_ADD
7 RETURN_VALUE
'exec'
accepts any kinds of python constructs from single expressions to whole modules of code, and executes them as if they were module top-level statements. The code object returns None
:
>>> dis.dis(compile('a + b', '<string>', 'exec'))
1 0 LOAD_NAME 0 (a)
3 LOAD_NAME 1 (b)
6 BINARY_ADD
7 POP_TOP <- discard result
8 LOAD_CONST 0 (None) <- load None on stack
11 RETURN_VALUE <- return top of stack
'single'
is a limited form of 'exec'
which accepts a source code containing a single statement (or multiple statements separated by ;
) if the last statement is an expression statement, the resulting bytecode also prints the repr
of the value of that expression to the standard output(!).
An if
-elif
-else
chain, a loop with else
, and try
with its except
, else
and finally
blocks is considered a single statement.
A source fragment containing 2 top-level statements is an error for the 'single'
, except in Python 2 there is a bug that sometimes allows multiple toplevel statements in the code; only the first is compiled; the rest are ignored:
In Python 2.7.8:
>>> exec(compile('a = 5\na = 6', '<string>', 'single'))
>>> a
5
And in Python 3.4.2:
>>> exec(compile('a = 5\na = 6', '<string>', 'single'))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1
a = 5
^
SyntaxError: multiple statements found while compiling a single statement
This is very useful for making interactive Python shells. However, the value of the expression is not returned, even if you eval
the resulting code.
Thus greatest distinction of exec
and eval
actually comes from the compile
function and its modes.
In addition to compiling source code to bytecode, compile
supports compiling abstract syntax trees (parse trees of Python code) into code
objects; and source code into abstract syntax trees (the ast.parse
is written in Python and just calls compile(source, filename, mode, PyCF_ONLY_AST)
); these are used for example for modifying source code on the fly, and also for dynamic code creation, as it is often easier to handle the code as a tree of nodes instead of lines of text in complex cases.
While eval
only allows you to evaluate a string that contains a single expression, you can eval
a whole statement, or even a whole module that has been compile
d into bytecode; that is, with Python 2, print
is a statement, and cannot be eval
led directly:
>>> eval('for i in range(3): print("Python is cool")')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1
for i in range(3): print("Python is cool")
^
SyntaxError: invalid syntax
compile
it with 'exec'
mode into a code
object and you can eval
it; the eval
function will return None
.
>>> code = compile('for i in range(3): print("Python is cool")',
'foo.py', 'exec')
>>> eval(code)
Python is cool
Python is cool
Python is cool
If one looks into eval
and exec
source code in CPython 3, this is very evident; they both call PyEval_EvalCode
with same arguments, the only difference being that exec
explicitly returns None
.
exec
between Python 2 and Python 3One of the major differences in Python 2 is that exec
is a statement and eval
is a built-in function (both are built-in functions in Python 3).
It is a well-known fact that the official syntax of exec
in Python 2 is exec code [in globals[, locals]]
.
Unlike majority of the Python 2-to-3 porting guides seem to suggest, the exec
statement in CPython 2 can be also used with syntax that looks exactly like the exec
function invocation in Python 3. The reason is that Python 0.9.9 had the exec(code, globals, locals)
built-in function! And that built-in function was replaced with exec
statement somewhere before Python 1.0 release.
Since it was desirable to not break backwards compatibility with Python 0.9.9, Guido van Rossum added a compatibility hack in 1993: if the code
was a tuple of length 2 or 3, and globals
and locals
were not passed into the exec
statement otherwise, the code
would be interpreted as if the 2nd and 3rd element of the tuple were the globals
and locals
respectively. The compatibility hack was not mentioned even in Python 1.4 documentation (the earliest available version online); and thus was not known to many writers of the porting guides and tools, until it was documented again in November 2012:
The first expression may also be a tuple of length 2 or 3. In this case, the optional parts must be omitted. The form
exec(expr, globals)
is equivalent toexec expr in globals
, while the formexec(expr, globals, locals)
is equivalent toexec expr in globals, locals
. The tuple form ofexec
provides compatibility with Python 3, whereexec
is a function rather than a statement.
Yes, in CPython 2.7 that it is handily referred to as being a forward-compatibility option (why confuse people over that there is a backward compatibility option at all), when it actually had been there for backward-compatibility for two decades.
Thus while exec
is a statement in Python 1 and Python 2, and a built-in function in Python 3 and Python 0.9.9,
>>> exec("print(a)", globals(), {'a': 42})
42
has had identical behaviour in possibly every widely released Python version ever; and works in Jython 2.5.2, PyPy 2.3.1 (Python 2.7.6) and IronPython 2.6.1 too (kudos to them following the undocumented behaviour of CPython closely).
What you cannot do in Pythons 1.0 - 2.7 with its compatibility hack, is to store the return value of exec
into a variable:
Python 2.7.11+ (default, Apr 17 2016, 14:00:29)
[GCC 5.3.1 20160413] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a = exec('print(42)')
File "<stdin>", line 1
a = exec('print(42)')
^
SyntaxError: invalid syntax
(which wouldn't be useful in Python 3 either, as exec
always returns None
), or pass a reference to exec
:
>>> call_later(exec, 'print(42)', delay=1000)
File "<stdin>", line 1
call_later(exec, 'print(42)', delay=1000)
^
SyntaxError: invalid syntax
Which a pattern that someone might actually have used, though unlikely;
Or use it in a list comprehension:
>>> [exec(i) for i in ['print(42)', 'print(foo)']
File "<stdin>", line 1
[exec(i) for i in ['print(42)', 'print(foo)']
^
SyntaxError: invalid syntax
which is abuse of list comprehensions (use a for
loop instead!).
In my case the issue is that on Xcode Beta 11.5 there's a change on the ways to sign the app so just make sure that both for the Debug/Release the provisioning certificate is properly set
Qt works very well with graphics. In my opinion it is more versatile than PIL.
You get all the features you want for graphics manipulation, but there's also vector graphics and even support for real printers. And all of that in one uniform API, QPainter
.
To use Qt you need a Python binding for it: PySide or PyQt4.
They both support Python 3.
Here is a simple example that loads a JPG image, draws an antialiased circle of radius 10 at coordinates (20, 20) with the color of the pixel that was at those coordinates and saves the modified image as a PNG file:
from PySide.QtCore import *
from PySide.QtGui import *
app = QCoreApplication([])
img = QImage('input.jpg')
g = QPainter(img)
g.setRenderHint(QPainter.Antialiasing)
g.setBrush(QColor(img.pixel(20, 20)))
g.drawEllipse(QPoint(20, 20), 10, 10)
g.end()
img.save('output.png')
But please note that this solution is quite 'heavyweight', because Qt is a large framework for making GUI applications.
You need to drop the table and then recreate it and then load it again
I tried the code by @alex-martelli but found some discrepancies
python -mtimeit -s "xs=range(123456)" "map(hex, xs)"
1000000 loops, best of 5: 218 nsec per loop
python -mtimeit -s "xs=range(123456)" "[hex(x) for x in xs]"
10 loops, best of 5: 19.4 msec per loop
map takes the same amount of time even for very large ranges while using list comprehension takes a lot of time as is evident from my code. So apart from being considered "unpythonic", I have not faced any performance issues relating to usage of map.
I just added this code to my service class so I could indirectly call OnStart, similar for OnStop.
public void MyOnStart(string[] args)
{
OnStart(args);
}
On Windows 10
insert at beggining this:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
Strange, but it works for me! (Together with input()
at the end, of course)
If you want to do it without any extra includes:
vector<IComponent*> myComponents; //assume it has items in it already.
void RemoveComponent(IComponent* componentToRemove)
{
IComponent* juggler;
if (componentToRemove != NULL)
{
for (int currComponentIndex = 0; currComponentIndex < myComponents.size(); currComponentIndex++)
{
if (componentToRemove == myComponents[currComponentIndex])
{
//Since we don't care about order, swap with the last element, then delete it.
juggler = myComponents[currComponentIndex];
myComponents[currComponentIndex] = myComponents[myComponents.size() - 1];
myComponents[myComponents.size() - 1] = juggler;
//Remove it from memory and let the vector know too.
myComponents.pop_back();
delete juggler;
}
}
}
}
just add C:\Program Files\Java\jdk1.7.0_80\bin as the path in environmental variables. no need to add java.exe and javac.exe to that path. IT WORKS
You can also use txml. It can parse into a DOM made of simple objects and stringify. In the result, the content will be trimmed. So formating of the original with whitespaces will be lost. But this could be used very good to minify HTML.
const xml = require('txml');
const data = `
<tag>tag content</tag>
<tag2>another content</tag2>
<tag3>
<insideTag>inside content</insideTag>
<emptyTag />
</tag3>`;
const dom = xml(data); // the dom can be JSON.stringified
xml.stringify(dom); // this will return the dom into an xml-string
Disclaimer: I am the author of txml, the fastest xml parser in javascript.
you set AllowRating property to true from your controller or model
@Html.CheckBoxFor(m => m.AllowRating, new { @checked =Model.AllowRating })
Hashes can not be decrypted check this out.
If you want to encrypt-decrypt, use a two way encryption function of your database like - AES_ENCRYPT (in MySQL).
But I'll suggest CRYPT_BLOWFISH algorithm for storing password. Read this- http://php.net/manual/en/function.crypt.php and http://us2.php.net/manual/en/function.password-hash.php
For Blowfish by crypt()
function -
crypt('String', '$2a$07$twentytwocharactersalt$');
password_hash
will be introduced in PHP 5.5.
$options = [
'cost' => 7,
'salt' => 'BCryptRequires22Chrcts',
];
password_hash("rasmuslerdorf", PASSWORD_BCRYPT, $options);
Once you have stored the password, you can then check if the user has entered correct password by hashing it again and comparing it with the stored value.
You can accomplish this (if I understand what you are trying to do) using dynamic SQL.
The trick is that you need to create a string containing the SQL statement. That's because the tablename has to specified in the actual SQL text, when you execute the statement. The table references and column references can't be supplied as parameters, those have to appear in the SQL text.
So you can use something like this approach:
SET @stmt = 'INSERT INTO @tmpTbl1 SELECT ' + @KeyValue
+ ' AS fld1 FROM tbl' + @KeyValue
EXEC (@stmt)
First, we create a SQL statement as a string. Given a @KeyValue of 'Foo', that would create a string containing:
'INSERT INTO @tmpTbl1 SELECT Foo AS fld1 FROM tblFoo'
At this point, it's just a string. But we can execute the contents of the string, as a dynamic SQL statement, using EXECUTE
(or EXEC
for short).
The old-school sp_executesql
procedure is an alternative to EXEC, another way to execute dymamic SQL, which also allows you to pass parameters, rather than specifying all values as literals in the text of the statement.
FOLLOWUP
EBarr points out (correctly and importantly) that this approach is susceptible to SQL Injection.
Consider what would happen if @KeyValue
contained the string:
'1 AS foo; DROP TABLE students; -- '
The string we would produce as a SQL statement would be:
'INSERT INTO @tmpTbl1 SELECT 1 AS foo; DROP TABLE students; -- AS fld1 ...'
When we EXECUTE that string as a SQL statement:
INSERT INTO @tmpTbl1 SELECT 1 AS foo;
DROP TABLE students;
-- AS fld1 FROM tbl1 AS foo; DROP ...
And it's not just a DROP TABLE that could be injected. Any SQL could be injected, and it might be much more subtle and even more nefarious. (The first attacks can be attempts to retreive information about tables and columns, followed by attempts to retrieve data (email addresses, account numbers, etc.)
One way to address this vulnerability is to validate the contents of @KeyValue, say it should contain only alphabetic and numeric characters (e.g. check for any characters not in those ranges using LIKE '%[^A-Za-z0-9]%'
. If an illegal character is found, then reject the value, and exit without executing any SQL.
Surprising to see nobody mentioned document.hasFocus
if (document.hasFocus()) console.log('Tab is active')
in my case, I Edit my gradle.properties
:
note: if u enable the minifyEnabled true
:
remove this line :
android.enableR8=true
and add this lines in ur build.gradle
, android
block :
dexOptions {
incremental = true
preDexLibraries = false
javaMaxHeapSize "4g" // 2g should be also OK
}
hope this help some one :)
Based on all the info on the post, I created a little script to make the whole process easy.
@ECHO OFF
netstat -aon |find /i "listening"
SET killport=
SET /P killport=Enter port:
IF "%killport%"=="" GOTO Kill
netstat -aon |find /i "listening" | find "%killport%"
:Kill
SET killpid=
SET /P killpid=Enter PID to kill:
IF "%killpid%"=="" GOTO Error
ECHO Killing %killpid%!
taskkill /F /PID %killpid%
GOTO End
:Error
ECHO Nothing to kill! Bye bye!!
:End
pause
You can delete the latest gradle-.-all folder from the below path Windows: C:\Users\your-username.gradle\wrapper\dists
You can use simply pd.to_datetime(then)
and pandas will convert the date elements into ISO date format- [YYYY-MM-DD]
.
You can pass this as map/apply to use it in a dataframe/series too.
You can use CSS3 transitions or maybe CSS3 animations to slide in an element.
For browser support: http://caniuse.com/
I made two quick examples just to show you how I mean.
CSS transition (on hover)
Relevant Code
.wrapper:hover #slide {
transition: 1s;
left: 0;
}
In this case, Im just transitioning the position from left: -100px;
to 0;
with a 1s. duration. It's also possible to move the element using transform: translate();
CSS animation
#slide {
position: absolute;
left: -100px;
width: 100px;
height: 100px;
background: blue;
-webkit-animation: slide 0.5s forwards;
-webkit-animation-delay: 2s;
animation: slide 0.5s forwards;
animation-delay: 2s;
}
@-webkit-keyframes slide {
100% { left: 0; }
}
@keyframes slide {
100% { left: 0; }
}
Same principle as above (Demo One), but the animation starts automatically after 2s, and in this case I've set animation-fill-mode
to forwards
, which will persist the end state, keeping the div visible when the animation ends.
Like I said, two quick example to show you how it could be done.
EDIT: For details regarding CSS Animations and Transitions see:
Animations
https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Using_CSS_animations
Transitions
https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Using_CSS_transitions
Hope this helped.
There is a new spec called the Native File System API that allows you to do this properly like this:
const result = await window.chooseFileSystemEntries({ type: "save-file" });
There is a demo here, but I believe it is using an origin trial so it may not work in your own website unless you sign up or enable a config flag, and it obviously only works in Chrome. If you're making an Electron app this might be an option though.
I had the same error and pip install MySQL-python
solved it for me.
Alternate installs:
easy_install MySQL-python
should work.sudo apt-get install ...
)Below, Soli notes that if you receive the following error:
EnvironmentError: mysql_config not found
... then you have a further system dependency issue. Solving this will vary from system to system, but for Debian-derived systems:
sudo apt-get install python-mysqldb
I just add this line of code into onCreate()
:
this.getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
Problem solved.
See the documentation for jQuery Event Target. Using the target property of the event object, you can detect where the click originated within the #menu_content
element and, if so, terminate the click handler early. You will have to use .closest()
to handle cases where the click originated in a descendant of #menu_content
.
$(document).click(function(e){
// Check if click was triggered on or within #menu_content
if( $(e.target).closest("#menu_content").length > 0 ) {
return false;
}
// Otherwise
// trigger your click function
});
Try this code
(case when CONVERT(VARCHAR(10), CreatedDate, 103) = '01/01/1900' then '' else CONVERT(VARCHAR(24), CreatedDate, 121) end) as Date_Resolved
I had tried below solution and it works for me, when concurrent request for insert statement occurs.
begin tran
if exists (select * from table with (updlock,serializable) where key = @key)
begin
update table set ...
where key = @key
end
else
begin
insert table (key, ...)
values (@key, ...)
end
commit tran
My answer is quite easy:
Use Entity Framework for communication between C# and your SQL database. That will make parameterized SQL strings that isn't vulnerable to SQL injection.
As a bonus, it's very easy to work with as well.
As MDN Window.history() describes :
For top-level pages you can see the list of pages in the session history, accessible via the History object, in the browser's dropdowns next to the back and forward buttons.
For security reasons the History object doesn't allow the non-privileged code to access the URLs of other pages in the session history, but it does allow it to navigate the session history.
There is no way to clear the session history or to disable the back/forward navigation from unprivileged code. The closest available solution is the location.replace() method, which replaces the current item of the session history with the provided URL.
So there is no Javascript method to clear the session history, instead, if you want to block navigating back to a certain page, you can use the location.replace() method, and pass the page link as parameter, which will not push the page to the browser's session history list. For example, there are three pages:
a.html:
<!doctype html>
<html>
<head>
<title>a.html page</title>
<meta charset="utf-8">
</head>
<body>
<p>This is <code style="color:red">a.html</code> page ! Go to <a href="b.html">b.html</a> page !</p>
</body>
</html>
b.html:
<!doctype html>
<html>
<head>
<title>b.html page</title>
<meta charset="utf-8">
</head>
<body>
<p>This is <code style="color:red">b.html</code> page ! Go to <a id="jumper" href="c.html">c.html</a> page !</p>
<script type="text/javascript">
var jumper = document.getElementById("jumper");
jumper.onclick = function(event) {
var e = event || window.event ;
if(e.preventDefault) {
e.preventDefault();
} else {
e.returnValue = true ;
}
location.replace(this.href);
jumper = null;
}
</script>
</body>
c.html:
<!doctype html>
<html>
<head>
<title>c.html page</title>
<meta charset="utf-8">
</head>
<body>
<p>This is <code style="color:red">c.html</code> page</p>
</body>
</html>
With href link, we can navigate from a.html to b.html to c.html. In b.html, we use the location.replace(c.html)
method to navigate from b.html to c.html. Finally, we go to c.html*, and if we click the back button in the browser, we will jump to **a.html.
So this is it! Hope it helps.
Pay attention to your colorAccent in your current Activity/fragment/Dialog, defined in Styles... ;) cursor color is related to it.
os.path.getsize(path)
Return the size, in bytes, of path. Raise os.error if the file does not exist or is inaccessible.
That delay you're talking about is actually a filter to prevent false (unwanted) orientation change notifications.
For instant recognition of device orientation change you're just gonna have to monitor the accelerometer yourself.
Accelerometer measures acceleration (gravity included) in all 3 axes so you shouldn't have any problems in figuring out the actual orientation.
Some code to start working with accelerometer can be found here:
How to make an iPhone App – Part 5: The Accelerometer
And this nice blog covers the math part:
@Josh Lindsey already answered perfectly fine. But I want to add some information since I often use ssh.
Therefore just change:
git remote add origin [email protected]:/path/to/my_project.git
to:
git remote add origin ssh://[email protected]/path/to/my_project
Note that the colon between domain and path isn't there anymore.
Just add an line of code in idle "input()"
I found this post helpful:
"It can happen when res folder contains unexpected folder names. In my case after merge mistakes I had a folder src/main/res/res. And it caused problems."
from: "https://groups.google.com/forum/#!msg/adt-dev/0pEUKhEBMIA/ZxO5FNRjF8QJ"
For me, the simplest way to do this is
1) Download and unzip bootstrap into vendor
2) Add the bootstrap path to your config
config.assets.paths << Rails.root.join("vendor/bootstrap-3.3.6-dist")
3) Require them
in css *= require css/bootstrap
in js //= require js/bootstrap
Done!
This methods makes the fonts load without any other special configuration and doesn't require moving the bootstrap files out of their self-contained directory.
nginx
, like all well-behaved programs, can be configured not to self-daemonize.
Use the daemon off
configuration directive described in http://wiki.nginx.org/CoreModule.
This is actually a documented feature, and can be found here
// This event listener calls addMarker() when the map is clicked.
google.maps.event.addListener(map, 'click', function(e) {
placeMarker(e.latLng, map);
});
function placeMarker(position, map) {
var marker = new google.maps.Marker({
position: position,
map: map
});
map.panTo(position);
}
declare @T int
set @T = 10455836
--set @T = 421151
select (@T / 1000000) % 100 as hour,
(@T / 10000) % 100 as minute,
(@T / 100) % 100 as second,
(@T % 100) * 10 as millisecond
select dateadd(hour, (@T / 1000000) % 100,
dateadd(minute, (@T / 10000) % 100,
dateadd(second, (@T / 100) % 100,
dateadd(millisecond, (@T % 100) * 10, cast('00:00:00' as time(2))))))
Result:
hour minute second millisecond
----------- ----------- ----------- -----------
10 45 58 360
(1 row(s) affected)
----------------
10:45:58.36
(1 row(s) affected)
The easiest way to create an object in JavaScript is to use the following syntax :
var test = {_x000D_
a : 5,_x000D_
b : 10,_x000D_
f : function(c) {_x000D_
return this.a + this.b + c;_x000D_
}_x000D_
}_x000D_
_x000D_
console.log(test);_x000D_
console.log(test.f(3));
_x000D_
This works great for storing data in a structured way.
For more complex use cases, however, it's often better to create instances of functions :
function Test(a, b) {_x000D_
this.a = a;_x000D_
this.b = b;_x000D_
this.f = function(c) {_x000D_
return this.a + this.b + c;_x000D_
};_x000D_
}_x000D_
_x000D_
var test = new Test(5, 10);_x000D_
console.log(test);_x000D_
console.log(test.f(3));
_x000D_
This allows you to create multiple objects that share the same "blueprint", similar to how you use classes in eg. Java.
This can still be done more efficiently, however, by using a prototype.
Whenever different instances of a function share the same methods or properties, you can move them to that object's prototype. That way, every instance of a function has access to that method or property, but it doesn't need to be duplicated for every instance.
In our case, it makes sense to move the method f
to the prototype :
function Test(a, b) {_x000D_
this.a = a;_x000D_
this.b = b;_x000D_
}_x000D_
_x000D_
Test.prototype.f = function(c) {_x000D_
return this.a + this.b + c;_x000D_
};_x000D_
_x000D_
var test = new Test(5, 10);_x000D_
console.log(test);_x000D_
console.log(test.f(3));
_x000D_
A simple but effective way to do inheritance in JavaScript, is to use the following two-liner :
B.prototype = Object.create(A.prototype);
B.prototype.constructor = B;
That is similar to doing this :
B.prototype = new A();
The main difference between both is that the constructor of A
is not run when using Object.create
, which is more intuitive and more similar to class based inheritance.
You can always choose to optionally run the constructor of A
when creating a new instance of B
by adding adding it to the constructor of B
:
function B(arg1, arg2) {
A(arg1, arg2); // This is optional
}
If you want to pass all arguments of B
to A
, you can also use Function.prototype.apply()
:
function B() {
A.apply(this, arguments); // This is optional
}
If you want to mixin another object into the constructor chain of B
, you can combine Object.create
with Object.assign
:
B.prototype = Object.assign(Object.create(A.prototype), mixin.prototype);
B.prototype.constructor = B;
function A(name) {_x000D_
this.name = name;_x000D_
}_x000D_
_x000D_
A.prototype = Object.create(Object.prototype);_x000D_
A.prototype.constructor = A;_x000D_
_x000D_
function B() {_x000D_
A.apply(this, arguments);_x000D_
this.street = "Downing Street 10";_x000D_
}_x000D_
_x000D_
B.prototype = Object.create(A.prototype);_x000D_
B.prototype.constructor = B;_x000D_
_x000D_
function mixin() {_x000D_
_x000D_
}_x000D_
_x000D_
mixin.prototype = Object.create(Object.prototype);_x000D_
mixin.prototype.constructor = mixin;_x000D_
_x000D_
mixin.prototype.getProperties = function() {_x000D_
return {_x000D_
name: this.name,_x000D_
address: this.street,_x000D_
year: this.year_x000D_
};_x000D_
};_x000D_
_x000D_
function C() {_x000D_
B.apply(this, arguments);_x000D_
this.year = "2018"_x000D_
}_x000D_
_x000D_
C.prototype = Object.assign(Object.create(B.prototype), mixin.prototype);_x000D_
C.prototype.constructor = C;_x000D_
_x000D_
var instance = new C("Frank");_x000D_
console.log(instance);_x000D_
console.log(instance.getProperties());
_x000D_
Object.create
can be safely used in every modern browser, including IE9+. Object.assign
does not work in any version of IE nor some mobile browsers. It is recommended to polyfill Object.create
and/or Object.assign
if you want to use them and support browsers that do not implement them.
You can find a polyfill for Object.create
here
and one for Object.assign
here.
Go to Path C:\ProgramData\Oracle\Java\javapath (This path is in my case might be different in your case). Rename the folder ORACLE with other name line ORACLE_OLD. And Restart the STS/IDE . This works for me
None of those methods work the way the questioner is asking for and which I've often had a need for as well. eg:
$ git remote
fatal: Not a git repository (or any of the parent directories): .git
$ git remote user@bserver
fatal: Not a git repository (or any of the parent directories): .git
$ git remote user@server:/home/user
fatal: Not a git repository (or any of the parent directories): .git
$ git ls-remote
fatal: No remote configured to list refs from.
$ git ls-remote user@server:/home/user
fatal: '/home/user' does not appear to be a git repository
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.
The whole point of doing this is that you do not have any information except the remote user and server and want to find out what you have access to.
The majority of the answers assume you are querying from within a git working set. The questioner is assuming you are not.
As a practical example, assume there was a repository foo.git on the server. Someone in their wisdom decides they need to change it to foo2.git. It would really be nice to do a list of a git directory on the server. And yes, I see the problems for git. It would still be nice to have though.
I'm using visual studio 2019 develop against ASP.Net application. Here's what been worked for us:
<authentication mode="Windows"></authentication>p
_x000D_
And I didn't change application.config in iis express.
In my case i had copied a classlibrary, and not changed the "Assembly Name" in the project properties, so one DLL was overwriting the other...
You may also try the Copy method:
File.Copy(@"c:\work\foo.txt", @"c:\data\bar.txt")
I have solved the same problem using the link with some modifications in it. Search filter on RecyclerView with Cards. Is it even possible? (hope this helps).
Here is my adapter class
public class ContactListRecyclerAdapter extends RecyclerView.Adapter<ContactListRecyclerAdapter.ContactViewHolder> implements Filterable {
Context mContext;
ArrayList<Contact> customerList;
ArrayList<Contact> parentCustomerList;
public ContactListRecyclerAdapter(Context context,ArrayList<Contact> customerList)
{
this.mContext=context;
this.customerList=customerList;
if(customerList!=null)
parentCustomerList=new ArrayList<>(customerList);
}
// other overrided methods
@Override
public Filter getFilter() {
return new FilterCustomerSearch(this,parentCustomerList);
}
}
//Filter class
import android.widget.Filter;
import java.util.ArrayList;
public class FilterCustomerSearch extends Filter
{
private final ContactListRecyclerAdapter mAdapter;
ArrayList<Contact> contactList;
ArrayList<Contact> filteredList;
public FilterCustomerSearch(ContactListRecyclerAdapter mAdapter,ArrayList<Contact> contactList) {
this.mAdapter = mAdapter;
this.contactList=contactList;
filteredList=new ArrayList<>();
}
@Override
protected FilterResults performFiltering(CharSequence constraint) {
filteredList.clear();
final FilterResults results = new FilterResults();
if (constraint.length() == 0) {
filteredList.addAll(contactList);
} else {
final String filterPattern = constraint.toString().toLowerCase().trim();
for (final Contact contact : contactList) {
if (contact.customerName.contains(constraint)) {
filteredList.add(contact);
}
else if (contact.emailId.contains(constraint))
{
filteredList.add(contact);
}
else if(contact.phoneNumber.contains(constraint))
filteredList.add(contact);
}
}
results.values = filteredList;
results.count = filteredList.size();
return results;
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
mAdapter.customerList.clear();
mAdapter.customerList.addAll((ArrayList<Contact>) results.values);
mAdapter.notifyDataSetChanged();
}
}
//Activity class
public class HomeCrossFadeActivity extends AppCompatActivity implements View.OnClickListener,OnFragmentInteractionListener,OnTaskCompletedListner
{
Fragment fragment;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_homecrossfadeslidingpane2);CardView mCard;
setContentView(R.layout.your_main_xml);}
//other overrided methods
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
MenuInflater inflater = getMenuInflater();
// Inflate menu to add items to action bar if it is present.
inflater.inflate(R.menu.menu_customer_view_and_search, menu);
// Associate searchable configuration with the SearchView
SearchManager searchManager =
(SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView =
(SearchView) menu.findItem(R.id.menu_search).getActionView();
searchView.setQueryHint("Search Customer");
searchView.setSearchableInfo(
searchManager.getSearchableInfo(getComponentName()));
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
if(fragment instanceof CustomerDetailsViewWithModifyAndSearch)
((CustomerDetailsViewWithModifyAndSearch)fragment).adapter.getFilter().filter(newText);
return false;
}
});
return true;
}
}
In OnQueryTextChangeListener() method use your adapter. I have casted it to fragment as my adpter is in fragment. You can use the adapter directly if its in your activity class.
The number of digits of an integer x
is equal to 1 + log10(x)
. So you can do this:
#include <math.h>
#include <stdio.h>
int main()
{
int x;
scanf("%d", &x);
printf("x has %d digits\n", 1 + (int)log10(x));
}
Or you can run a loop to count the digits yourself: do integer division by 10 until the number is 0:
int numDigits = 0;
do
{
++numDigits;
x = x / 10;
} while ( x );
You have to be a bit careful to return 1
if the integer is 0
in the first solution and you might also want to treat negative integers (work with -x
if x < 0
).
For #2 args will be only a formal parameter with dict value, but not a keyword type parameter.
If you want to pass a keyword type parameter into a keyword argument You need to specific ** before your dictionary, which means **args
check this out for more detail on using **kw
http://www.saltycrane.com/blog/2008/01/how-to-use-args-and-kwargs-in-python/
This is a working code
imageView.setDrawingCacheEnabled(true);
imageView.buildDrawingCache();
Bitmap bitmap = Bitmap.createBitmap(imageView.getDrawingCache());
Suppose User has_many Posts:
u = User.first
u.posts.methods
u.posts.methods - Object.methods
if [[ $gg =~ ^....grid.* ]]
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
System.out.println(dateFormat.format(date));
found here
You can create the ordered dict from old dict in one line:
from collections import OrderedDict
ordered_dict = OrderedDict(sorted(ship.items())
The default sorting key is by dictionary key, so the new ordered_dict
is sorted by old dict's keys.
DTO
is an abbreviation for Data Transfer Object, so it is used to transfer the data between classes and modules of your application.
DTO
should only contain private fields for your data, getters, setters, and constructors.DTO
is not recommended to add business logic methods to such classes, but it is OK to add some util methods.DAO
is an abbreviation for Data Access Object, so it should encapsulate the logic for retrieving, saving and updating data in your data storage (a database, a file-system, whatever).
Here is an example of how the DAO and DTO interfaces would look like:
interface PersonDTO {
String getName();
void setName(String name);
//.....
}
interface PersonDAO {
PersonDTO findById(long id);
void save(PersonDTO person);
//.....
}
The MVC
is a wider pattern. The DTO/DAO would be your model in the MVC pattern.
It tells you how to organize the whole application, not just the part responsible for data retrieval.
As for the second question, if you have a small application it is completely OK, however, if you want to follow the MVC pattern it would be better to have a separate controller, which would contain the business logic for your frame in a separate class and dispatch messages to this controller from the event handlers.
This would separate your business logic from the view.
For a checked exception:
public class MyCustomException extends Exception { }
Technically, anything that extends Throwable
can be an thrown, but exceptions are generally extensions of the Exception
class so that they're checked exceptions (except RuntimeException or classes based on it, which are not checked), as opposed to the other common type of throwable, Error
s which usually are not something designed to be gracefully handled beyond the JVM internals.
You can also make exceptions non-public, but then you can only use them in the package that defines them, as opposed to across packages.
As far as throwing/catching custom exceptions, it works just like the built-in ones - throw via
throw new MyCustomException()
and catch via
catch (MyCustomException e) { }
If the databases share server, have a login that has priveleges to both of the databases, and simply have a query run similiar to:
$query = $this->db->query("
SELECT t1.*, t2.id
FROM `database1`.`table1` AS t1, `database2`.`table2` AS t2
");
Otherwise I think you might have to run the 2 queries separately and fix the logic afterwards.
The ArrayList uses the equals method implemented in the class (your case Thing class) to do the equals comparison.
Another approach to solve this, question:
public class CollectionUtils {
/**
* Splits the collection into lists with given batch size
* @param collection to split in to batches
* @param batchsize size of the batch
* @param <T> it maintains the input type to output type
* @return nested list
*/
public static <T> List<List<T>> makeBatch(Collection<T> collection, int batchsize) {
List<List<T>> totalArrayList = new ArrayList<>();
List<T> tempItems = new ArrayList<>();
Iterator<T> iterator = collection.iterator();
for (int i = 0; i < collection.size(); i++) {
tempItems.add(iterator.next());
if ((i+1) % batchsize == 0) {
totalArrayList.add(tempItems);
tempItems = new ArrayList<>();
}
}
if (tempItems.size() > 0) {
totalArrayList.add(tempItems);
}
return totalArrayList;
}
}
This happened to me with Visual Studio 2013 Web, after Windows installed several updates. Unfortunately none of the suggestions in this thread helped.
I had to re-run the installer and select the "Repair" option. After that (and a reboot) it was working once again.
In some cases you may have to repair more than one version of Visual Studio. One example is when a Script Task control in VS 2013 opens VS 2012 when you click Edit Script.
Use the inbuilt function in PHP, implode(array, separator)
:
<?php
$ar = array("parth","raja","nikhar");
echo implode($ar,"/");
?>
Result: parth/raja/nikhar
I believe that is just how the browser renders their standard input. If you set a border on the input:
<input type="text" style="width: 10px; padding: 2px; border: 1px solid black"/>
<div style="width: 10px; border: solid 1px black; padding: 2px"> </div>
Then both are the same width, at least in FF.
Xcode > Preferences > Locations > Command Line Tools
Select the option matching your version of Xcode.
How about the regex way:
String s = "001234-a";
s = s.replaceFirst ("^0*", "");
The ^
anchors to the start of the string (I'm assuming from context your strings are not multi-line here, otherwise you may need to look into \A
for start of input rather than start of line). The 0*
means zero or more 0
characters (you could use 0+
as well). The replaceFirst
just replaces all those 0
characters at the start with nothing.
And if, like Vadzim, your definition of leading zeros doesn't include turning "0"
(or "000"
or similar strings) into an empty string (a rational enough expectation), simply put it back if necessary:
String s = "00000000";
s = s.replaceFirst ("^0*", "");
if (s.isEmpty()) s = "0";
Installing bzip2
and zip
PHP extensions solved my issue in Ubuntu:
sudo apt-get install php7.0-bz2
sudo apt-get install php7.0-zip
Use php(you version)-(extension)
to install and enable any missing modules that is required in the phpmyadmin readme.
I would create a user control which holds a Label and a Text Box in it and simply create instances of that user control 'n' times. If you want to know a better way to do it and use properties to get access to the values of Label and Text Box from the user control, please let me know.
Simple way to do it would be:
int n = 4; // Or whatever value - n has to be global so that the event handler can access it
private void btnDisplay_Click(object sender, EventArgs e)
{
TextBox[] textBoxes = new TextBox[n];
Label[] labels = new Label[n];
for (int i = 0; i < n; i++)
{
textBoxes[i] = new TextBox();
// Here you can modify the value of the textbox which is at textBoxes[i]
labels[i] = new Label();
// Here you can modify the value of the label which is at labels[i]
}
// This adds the controls to the form (you will need to specify thier co-ordinates etc. first)
for (int i = 0; i < n; i++)
{
this.Controls.Add(textBoxes[i]);
this.Controls.Add(labels[i]);
}
}
The code above assumes that you have a button btnDisplay
and it has a onClick
event assigned to btnDisplay_Click
event handler. You also need to know the value of n and need a way of figuring out where to place all controls. Controls should have a width and height specified as well.
To do it using a User Control simply do this.
Okay, first of all go and create a new user control and put a text box and label in it.
Lets say they are called txtSomeTextBox
and lblSomeLabel
. In the code behind add this code:
public string GetTextBoxValue()
{
return this.txtSomeTextBox.Text;
}
public string GetLabelValue()
{
return this.lblSomeLabel.Text;
}
public void SetTextBoxValue(string newText)
{
this.txtSomeTextBox.Text = newText;
}
public void SetLabelValue(string newText)
{
this.lblSomeLabel.Text = newText;
}
Now the code to generate the user control will look like this (MyUserControl is the name you have give to your user control):
private void btnDisplay_Click(object sender, EventArgs e)
{
MyUserControl[] controls = new MyUserControl[n];
for (int i = 0; i < n; i++)
{
controls[i] = new MyUserControl();
controls[i].setTextBoxValue("some value to display in text");
controls[i].setLabelValue("some value to display in label");
// Now if you write controls[i].getTextBoxValue() it will return "some value to display in text" and controls[i].getLabelValue() will return "some value to display in label". These value will also be displayed in the user control.
}
// This adds the controls to the form (you will need to specify thier co-ordinates etc. first)
for (int i = 0; i < n; i++)
{
this.Controls.Add(controls[i]);
}
}
Of course you can create more methods in the usercontrol to access properties and set them. Or simply if you have to access a lot, just put in these two variables and you can access the textbox and label directly:
public TextBox myTextBox;
public Label myLabel;
In the constructor of the user control do this:
myTextBox = this.txtSomeTextBox;
myLabel = this.lblSomeLabel;
Then in your program if you want to modify the text value of either just do this.
control[i].myTextBox.Text = "some random text"; // Same applies to myLabel
Hope it helped :)
Converting the String to JsonNode using ObjectMapper object :
ObjectMapper mapper = new ObjectMapper();
// For text string
JsonNode = mapper.readValue(mapper.writeValueAsString("Text-string"), JsonNode.class)
// For Array String
JsonNode = mapper.readValue("[\"Text-Array\"]"), JsonNode.class)
// For Json String
String json = "{\"id\" : \"1\"}";
ObjectMapper mapper = new ObjectMapper();
JsonFactory factory = mapper.getFactory();
JsonParser jsonParser = factory.createParser(json);
JsonNode node = mapper.readTree(jsonParser);
A set is an unordered group of distinct objects — no duplicate objects are allowed. It is generally implemented using the hash code of the objects being inserted. (Specific implementations may add ordering, but the Set interface itself does not.)
A list is an ordered group of objects which may contain duplicates. It could be implemented with an ArrayList
, LinkedList
, etc.
You have to add this to your pg_hba.conf and restart your PostgreSQL.
host all all 192.168.56.1/24 md5
This works with VirtualBox and host-only adapter enabled. If you don't use Virtualbox you have to replace the IP address.
(?<=\[).+?(?=\])
Will capture content without brackets
(?<=\[)
- positive lookbehind for [
.*?
- non greedy match for the content
(?=\])
- positive lookahead for ]
EDIT: for nested brackets the below regex should work:
(\[(?:\[??[^\[]*?\]))
Use str.join
:
In [27]: mylist = ['10', '12', '14']
In [28]: print '\n'.join(mylist)
10
12
14
This is not possible. To create a table you need a table schema. What you have is a data file. A schema cannot be created with it.
What you can do is check if your file has a header row, and, in that case, you can manually create a table using that header row.
However, there is a way to generate a create table statement using a batch file as described by John Swapceinski in the comment section of the MySQL manual.
Posted by John Swapceinski on September 5 2011 5:33am.
Create a table using the .csv file's header:
#!/bin/sh
# pass in the file name as an argument: ./mktable filename.csv
echo "create table $1 ( "
head -1 $1 | sed -e 's/,/ varchar(255),\n/g'
echo " varchar(255) );"
Okay, I'll write another instruction, because didn't find the clear answer here. So if you faced such problems, follow this:
You should not just create empty .env file, but fill it with content of .env.example.
php artisan key:generate
Application key [base64:wbvPP9pBOwifnwu84BeKAVzmwM4TLvcVFowLcPAi6nA=] set successfully.
APP_KEY=base64:wbvPP9pBOwifnwu84BeKAVzmwM4TLvcVFowLcPAi6nA=
php artisan config:cache
That's it.
Well I know this answer is not an experienced programmer's approach and of an Old It consultant , but it worked for me .
the answer is "TRY TURNING IT ON AND OFF" . restart codeblocks and it works well reminds me of the 2006 comedy show It Crowd .
Try this:
select distinct a.FirstName, a.LastName, v.District
from AddTbl a
inner join ValTbl v
on a.LastName = v.LastName
order by a.FirstName;
Or this (it does the same, but the syntax is different):
select distinct a.FirstName, a.LastName, v.District
from AddTbl a, ValTbl v
where a.LastName = v.LastName
order by a.FirstName;
As you use Joda Time, you should use DateTimeFormatter
:
final DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MMM-dd");
final LocalDate dt = dtf.parseLocalDate(yourinput);
If using Java 8 or later, then refer to hertzi's answer
git config --global core.askpass "git-gui--askpass"
This worked for me. It may take 3-5 secs for the prompt to appear just enter your login credentials and you are good to go.
String word = "blah blah";
for(int i =0;i<word.length;++i)
{
if(Character.isLowerCase(word.charAt(i)){
System.out.print((int)word.charAt(i) - (int)'a'+1);
}
else{
System.out.print((int)word.charAt(i)-(int)'A' +1);
}
}
constructor(private router: Router) {}
navigateOnParent() {
this.router.navigate(['../some-path-on-parent']);
}
The router supports
/xxx
- started on the router of the root componentxxx
- started on the router of the current component../xxx
- started on the parent router of the current componentI had the same error at first and i was really annoyed.
you just need to have ./
before the path to the template
res.render('./index/index');
Hope it works, worked for me.
I was getting e.data.indexOf is not a function
error, after debugging it, I found that it was actually a TypeError
, which meant, indexOf()
being a function is applicable to strings, so I typecasted the data like the following and then used the indexOf()
method to make it work
e.data.toString().indexOf('<stringToBeMatchedToPosition>')
Not sure if my answer was accurate to the question, but yes shared my opinion as i faced a similar kind of situation.
Follow the screenshot below. It works when you run the simulator (won't see it on preview)
As others said, you may run your external program without xterm. However, if you want to run it in a terminal window, e.g. to let the user interact with it, xterm allows you to specify the program to run as parameter.
xterm -e any command
In Java code this becomes:
String[] command = { "xterm", "-e", "my", "command", "with", "parameters" };
Runtime.getRuntime().exec(command);
Or, using ProcessBuilder:
String[] command = { "xterm", "-e", "my", "command", "with", "parameters" };
Process proc = new ProcessBuilder(command).start();
Or if you need to set the value of found:
found = Value1.StartsWith("abc")
Edit: Given your edit, I would do something like:
found = Value1.Substring(0, 5).Contains("abc")