The accepted answer explains already well why the warning occurs. If you simply want to control the warnings, one could use precision_recall_fscore_support
. It offers a (semi-official) argument warn_for
that could be used to mute the warnings.
(_, _, f1, _) = metrics.precision_recall_fscore_support(y_test, y_pred,
average='weighted',
warn_for=tuple())
As mentioned already in some comments, use this with care.
I had a similar problem but using IntelliJ IDEA rather than Eclipse. I already had the ARM EABI installed, but I still got the error.
For IntelliJ IDEA, it appears you also have to create an AVB first before running the emulator, so to do this you must just go into Android SDK Manager and create a new AVB. This should solve your problem... Please make sure you have followed the above answer to include the ARM before following these steps.
You'd treat one of the files as a python module and make the other one import it (just as you import standard python modules). The latter can then refer to objects (including classes and functions) defined in the imported module. The module can also run whatever initialization code it needs. See http://docs.python.org/tutorial/modules.html
Here's how I have it. The hint didn't show on my console until I updated npm a couple of days prior.
.connect has three parameters, the URI, options, and err.
mongoose.connect(
keys.getDbConnectionString(),
{ useNewUrlParser: true },
err => {
if (err)
throw err;
console.log(`Successfully connected to database.`);
}
);
It seems this is one of the rare occasions on which use of an attribute is actually appropriate. jQuery's attr()
method will not help you because in most cases (including this) it actually sets a property, not an attribute, making the choice of its name look somewhat foolish. [UPDATE: Since jQuery 1.6.1, the situation has changed slightly]
IE has some problems with the DOM setAttribute
method but in this case it should be fine:
this.setAttribute("checked", "checked");
In IE, this will always actually make the checkbox checked. In other browsers, if the user has already checked and unchecked the checkbox, setting the attribute will have no visible effect. Therefore, if you want to guarantee the checkbox is checked as well as having the checked
attribute, you need to set the checked
property as well:
this.setAttribute("checked", "checked");
this.checked = true;
To uncheck the checkbox and remove the attribute, do the following:
this.setAttribute("checked", ""); // For IE
this.removeAttribute("checked"); // For other browsers
this.checked = false;
For me it also was problem with path, but I had percentage sign in the root folder.
After I replaced %20 with space, it started to work :)
Try this. You can just use built-in ThresholdFilter
and LevelFilter
. No need to create your own filters programmically. In this example WARN and ERROR levels are logged to System.err and rest to System.out:
<appender name="stdout" class="ch.qos.logback.core.ConsoleAppender">
<!-- deny ERROR level -->
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>ERROR</level>
<onMatch>DENY</onMatch>
</filter>
<!-- deny WARN level -->
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>WARN</level>
<onMatch>DENY</onMatch>
</filter>
<target>System.out</target>
<immediateFlush>true</immediateFlush>
<encoder>
<charset>utf-8</charset>
<pattern>${msg_pattern}</pattern>
</encoder>
</appender>
<appender name="stderr" class="ch.qos.logback.core.ConsoleAppender">
<!-- deny all events with a level below WARN, that is INFO, DEBUG and TRACE -->
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>WARN</level>
</filter>
<target>System.err</target>
<immediateFlush>true</immediateFlush>
<encoder>
<charset>utf-8</charset>
<pattern>${msg_pattern}</pattern>
</encoder>
</appender>
<root level="WARN">
<appender-ref ref="stderr"/>
</root>
<root level="TRACE">
<appender-ref ref="stdout"/>
</root>
This is overly complicated, Jackson handles lists via its writer methods just as well as it handles regular objects. This should work just fine for you, assuming I have not misunderstood your question:
public void writeListToJsonArray() throws IOException {
final List<Event> list = new ArrayList<Event>(2);
list.add(new Event("a1","a2"));
list.add(new Event("b1","b2"));
final ByteArrayOutputStream out = new ByteArrayOutputStream();
final ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(out, list);
final byte[] data = out.toByteArray();
System.out.println(new String(data));
}
This is really more of a serverfault-type question, but you can use netstat.
something like:
# netstat -lpnt | grep 6000 | grep ssh
This will tell you if there's an ssh process listening on the specified port. it will also tell you the PID of the process.
If you really want to double-check that the ssh process was started with the right options, you can then look up the process by PID in something like
# ps aux | grep PID
Here is a comparison of several different ways to create a singleton in Dart.
class SingletonOne {
SingletonOne._privateConstructor();
static final SingletonOne _instance = SingletonOne._privateConstructor();
factory SingletonOne() {
return _instance;
}
}
class SingletonTwo {
SingletonTwo._privateConstructor();
static final SingletonTwo _instance = SingletonTwo._privateConstructor();
static SingletonTwo get instance => _instance;
}
class SingletonThree {
SingletonThree._privateConstructor();
static final SingletonThree instance = SingletonThree._privateConstructor();
}
The above singletons are instantiated like this:
SingletonOne one = SingletonOne();
SingletonTwo two = SingletonTwo.instance;
SingletonThree three = SingletonThree.instance;
Note:
I originally asked this as a question, but discovered that all of the methods above are valid and the choice largely depends on personal preference.
In case it is an Android gradle project - you can find the android libraries below your $ANDROID_HOME/extras/android/m2repository folder
We can see the null values present in the dataset by generating heatmap using seaborn moduleheatmap
import pandas as pd
import seaborn as sns
dataset=pd.read_csv('train.csv')
sns.heatmap(dataset.isnull(),cbar=False)
This worked well for me.
<Style x:Key="TransparentStyle" TargetType="{x:Type Button}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Border>
<Border.Style>
<Style TargetType="{x:Type Border}">
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="DarkGoldenrod"/>
</Trigger>
</Style.Triggers>
</Style>
</Border.Style>
<Grid Background="Transparent">
<ContentPresenter></ContentPresenter>
</Grid>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Button Style="{StaticResource TransparentStyle}" VerticalAlignment="Top" HorizontalAlignment="Right" Width="25" Height="25"
Command="{Binding CloseWindow}">
<Button.Content >
<Grid Margin="0 0 0 0">
<Path Data="M0,7 L10,17 M0,17 L10,7" Stroke="Blue" StrokeThickness="2" HorizontalAlignment="Center" Stretch="None" />
</Grid>
</Button.Content>
</Button>
I worked a little with RecyclerView
and still prefer ListView
.
Sure, both of them use ViewHolders
, so this is not an advantage.
A RecyclerView
is more difficult in coding.
A RecyclerView
doesn't contain a header and footer, so it's a minus.
A ListView
doesn't require to make a ViewHolder. In cases where you want to have a list with sections or subheaders it would be a good idea to make independent items (without a ViewHolder), it's easier and doesn't require separate classes.
Like andynormancx' post, use this (if you're working in an Unix environment):
scriptname > /dev/null
Or you can use this (if you're working in a Windows environment):
scriptname > nul
google-services.json file work like API keys means it store your project_id and api key with json format for all google services(Which enable by you at google console) so no need manage all at different places.
at application gradle you should add
apply plugin: 'com.google.gms.google-services'.
at top level gradle you should add below dependency
dependencies {
// Add this line
classpath 'com.google.gms:google-services:3.0.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
Mount the certs onto the Docker container using -v
:
docker run -v /host/path/to/certs:/container/path/to/certs -d IMAGE_ID "update-ca-certificates"
Use sqlcmd instead of osql if it's a 2005 database
If you want to add AUTO_INCREMENT in an existing table, need to run following SQL command:
ALTER TABLE users ADD id int NOT NULL AUTO_INCREMENT primary key
Try with below logic
driver.get("http://www.labmultis.info/jpecka.portal-exdrazby/index.php?c1=2&a=s&aa=&ta=1");
List<WebElement> allElements=driver.findElements(By.cssSelector(".list.list-categories li"));
for(WebElement ele :allElements) {
System.out.println("Name + Number===>"+ele.getText());
String s=ele.getText();
s=s.substring(s.indexOf("(")+1, s.indexOf(")"));
System.out.println("Number==>"+s);
}
====Output======
Name + Number===>Vše (950)
Number==>950
Name + Number===>Byty (181)
Number==>181
Name + Number===>Domy (512)
Number==>512
Name + Number===>Pozemky (172)
Number==>172
Name + Number===>Chaty (28)
Number==>28
Name + Number===>Zemedelské objekty (5)
Number==>5
Name + Number===>Komercní objekty (30)
Number==>30
Name + Number===>Ostatní (22)
Number==>22
In order to insert the first record set of a stored procedure into a temporary table you need to know the following:
sp_executesql
)The above may look as limitation, but IMHO it perfectly makes sense - if you are using sp_executesql
you can once return two columns and once ten, and if you have multiple result sets, you cannot insert them into several tables as well - you can insert maximum in two table in one T-SQL statement (using OUTPUT
clause and no triggers).
So, the issue is mainly how to define the temporary table structure before performing the EXEC ... INTO ...
statement.
The first works with OBJECT_ID
while the second and the third works with Ad-hoc queries as well. I prefer to use the DMV instead of the sp as you can use CROSS APPLY
and build the temporary table definitions for multiple procedures at the same time.
SELECT p.name, r.*
FROM sys.procedures AS p
CROSS APPLY sys.dm_exec_describe_first_result_set_for_object(p.object_id, 0) AS r;
Also, pay attention to the system_type_name
field as it can be very useful. It stores the column complete definition. For, example:
smalldatetime
nvarchar(max)
uniqueidentifier
nvarchar(1000)
real
smalldatetime
decimal(18,2)
and you can use it directly in most of the cases to create the table definition.
So, I think in most of the cases (if the stored procedure match certain criteria) you can easily build dynamic statements for solving such issues (create the temporary table, insert the stored procedure result in it, do what you need with the data).
Note, that the objects above fail to define the first result set data in some cases like when dynamic T-SQL statements are executed or temporary tables are used in the stored procedure.
Another way would be something like this, the idea here is to use grouper, but get rid of None
. In this case we'll have all 'small_parts' formed from elements at the first part of the list, and 'larger_parts' from the later part of the list. Length of 'larger parts' is len(small_parts) + 1. We need to consider x as two different sub-parts.
from itertools import izip_longest
import numpy as np
def grouper(n, iterable, fillvalue=None): # This is grouper from itertools
"grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
args = [iter(iterable)] * n
return izip_longest(fillvalue=fillvalue, *args)
def another_chunk(x,num):
extra_ele = len(x)%num #gives number of parts that will have an extra element
small_part = int(np.floor(len(x)/num)) #gives number of elements in a small part
new_x = list(grouper(small_part,x[:small_part*(num-extra_ele)]))
new_x.extend(list(grouper(small_part+1,x[small_part*(num-extra_ele):])))
return new_x
The way I have it set up returns a list of tuples:
>>> x = range(14)
>>> another_chunk(x,3)
[(0, 1, 2, 3), (4, 5, 6, 7, 8), (9, 10, 11, 12, 13)]
>>> another_chunk(x,4)
[(0, 1, 2), (3, 4, 5), (6, 7, 8, 9), (10, 11, 12, 13)]
>>> another_chunk(x,5)
[(0, 1), (2, 3, 4), (5, 6, 7), (8, 9, 10), (11, 12, 13)]
>>>
Using CSS3 you don't need to make your own image with the transparency.
Just have a div with the following
position:absolute;
left:0;
background: rgba(255,255,255,.5);
The last parameter in background (.5) is the level of transparency (a higher number is more opaque).
There is nothing out of the box that is comparable to velocity since velocity was written to solve exactly that problem. The closest thing you can try is looking into the Formatter
However the formatter as far as I know was created to provide C like formatting options in Java so it may not scratch exactly your itch but you are welcome to try :).
This command should work if the others did not solve the problem:
sudo asterisk -&
From Docker 17.06 onwards, a special Mac-only DNS name is available in docker containers that resolves to the IP address of the host. It is:
docker.for.mac.localhost
The documentation is here: https://docs.docker.com/docker-for-mac/networking/#httphttps-proxy-support
There is nice tiny library to work with utf8 from c++: utfcpp
@HankCa solved the problem in my case as well. I decided to change my dangerous **/*.jar
ignores to self-explanatory ones like src/**/lib/*.jar
to avoid such problems in the future. Ignores starting with **/* are a bit too hazardous, at least to me. And it's always a good idea to get the idea behind a .gitignore row just by looking at it.
Using HTML5 and the File API
The images sources will be a URL representing the Blob object
<img src="blob:null/026cceb9-edr4-4281-babb-b56cbf759a3d">
const EL_browse = document.getElementById('browse');_x000D_
const EL_preview = document.getElementById('preview');_x000D_
_x000D_
const readImage = file => {_x000D_
if ( !(/^image\/(png|jpe?g|gif)$/).test(file.type) )_x000D_
return EL_preview.insertAdjacentHTML('beforeend', `Unsupported format ${file.type}: ${file.name}<br>`);_x000D_
_x000D_
const img = new Image();_x000D_
img.addEventListener('load', () => {_x000D_
EL_preview.appendChild(img);_x000D_
EL_preview.insertAdjacentHTML('beforeend', `<div>${file.name} ${img.width}×${img.height} ${file.type} ${Math.round(file.size/1024)}KB<div>`);_x000D_
window.URL.revokeObjectURL(img.src); // Free some memory_x000D_
});_x000D_
img.src = window.URL.createObjectURL(file);_x000D_
}_x000D_
_x000D_
EL_browse.addEventListener('change', ev => {_x000D_
EL_preview.innerHTML = ''; // Remove old images and data_x000D_
const files = ev.target.files;_x000D_
if (!files || !files[0]) return alert('File upload not supported');_x000D_
[...files].forEach( readImage );_x000D_
});
_x000D_
#preview img { max-height: 100px; }
_x000D_
<input id="browse" type="file" multiple>_x000D_
<div id="preview"></div>
_x000D_
In case you need images sources as long Base64 encoded data strings
<img src="data:image/png;base64,iVBORw0KGg... ...lF/++TkSuQmCC=">
const EL_browse = document.getElementById('browse');_x000D_
const EL_preview = document.getElementById('preview');_x000D_
_x000D_
const readImage = file => {_x000D_
if ( !(/^image\/(png|jpe?g|gif)$/).test(file.type) )_x000D_
return EL_preview.insertAdjacentHTML('beforeend', `<div>Unsupported format ${file.type}: ${file.name}</div>`);_x000D_
_x000D_
const reader = new FileReader();_x000D_
reader.addEventListener('load', () => {_x000D_
const img = new Image();_x000D_
img.addEventListener('load', () => {_x000D_
EL_preview.appendChild(img);_x000D_
EL_preview.insertAdjacentHTML('beforeend', `<div>${file.name} ${img.width}×${img.height} ${file.type} ${Math.round(file.size/1024)}KB</div>`);_x000D_
});_x000D_
img.src = reader.result;_x000D_
});_x000D_
reader.readAsDataURL(file); _x000D_
};_x000D_
_x000D_
EL_browse.addEventListener('change', ev => {_x000D_
EL_preview.innerHTML = ''; // Clear Preview_x000D_
const files = ev.target.files;_x000D_
if (!files || !files[0]) return alert('File upload not supported');_x000D_
[...files].forEach( readImage );_x000D_
});
_x000D_
#preview img { max-height: 100px; }
_x000D_
<input id="browse" type="file" multiple>_x000D_
<div id="preview"></div>_x000D_
_x000D_
You must to have installed php_openssl.dll, if you use wampserver it's pretty easy, search and apply the extension for PHP.
In the example change this:
//Set the hostname of the mail server
$mail->Host = 'smtp.gmail.com';
//Set the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission 465 ssl
$mail->Port = 465;
//Set the encryption system to use - ssl (deprecated) or tls
$mail->SMTPSecure = 'ssl';
and then you recived an email from gmail talking about to enable the option to Less Safe Access Applications here https://www.google.com/settings/security/lesssecureapps
I recommend you change the password and encrypt it constantly
The current version allows the cv::Mat::at
function to handle 3 dimensions. So for a Mat
object m
, m.at<uchar>(0,0,0)
should work.
A Textblock itself can't do vertical alignment
The best way to do this that I've found is to put the textblock inside a border, so the border does the alignment for you.
<Border BorderBrush="{x:Null}" Height="50">
<TextBlock TextWrapping="Wrap" Text="Some Text" VerticalAlignment="Center"/>
</Border>
Note: This is functionally equivalent to using a grid, it just depends how you want the controls to fit in with the rest of your layout as to which one is more suitable
We can write directly too...
DECLARE @SearchLetter CHAR(1)
SET @SearchLetter = 'A'
SELECT *
FROM CUSTOMERS
WHERE CONTACTNAME LIKE @SearchLetter + '%'
AND REGION = 'WY'
or the following way as well if we have to append all the search characters then,
DECLARE @SearchLetter CHAR(1)
SET @SearchLetter = 'A' + '%'
SELECT *
FROM CUSTOMERS
WHERE CONTACTNAME LIKE @SearchLetter
AND REGION = 'WY'
Both these will work
fetchTimeout (url,options,timeout=3000) {
return new Promise( (resolve, reject) => {
fetch(url, options)
.then(resolve,reject)
setTimeout(reject,timeout);
})
}
I was able to update it with markForCheck()
Import ChangeDetectorRef
import { ChangeDetectorRef } from '@angular/core';
Inject and instantiate it
constructor(private ref: ChangeDetectorRef) {
}
Finally mark change detection to take place
this.ref.markForCheck();
Here's an example where markForCheck() works and detectChanges() don't.
https://plnkr.co/edit/RfJwHqEVJcMU9ku9XNE7?p=preview
EDIT: This example doesn't portray the problem anymore :( I believe it might be running a newer Angular version where it's fixed.
(Press STOP/RUN to run it again)
Actually it's java limitation caping it at 2^30-4 being 1073741820. Not 2^31-1. Dunno why but i tested it manually on jdk. 2^30-3 still throwing vm except
Edit: fixed -1 to -4, checked on windows jvm
JFrame.dispose()
public void dispose()
Releases all of the native screen resources used by this Window, its subcomponents, and all of its owned children. That is, the resources for these Components will be destroyed, any memory they consume will be returned to the OS, and they will be marked as undisplayable. The Window and its subcomponents can be made displayable again by rebuilding the native resources with a subsequent call to pack or show. The states of the recreated Window and its subcomponents will be identical to the states of these objects at the point where the Window was disposed (not accounting for additional modifications between those actions).
Note: When the last displayable window within the Java virtual machine (VM) is disposed of, the VM may terminate. See AWT Threading Issues for more information.
System.exit()
public static void exit(int status)
Terminates the currently running Java Virtual Machine. The argument serves as a status code; by convention, a nonzero status code indicates abnormal termination. This method calls the exit method in class Runtime. This method never returns normally.
The call System.exit(n)
is effectively equivalent to the call:
Runtime.getRuntime().exit(n)
I found the answer to the second part of my questions. Yes, a class can implement an interface that is in a different class as long that the interface is declared as public.
Use the left
function:
QString yourString = "This is a string";
QString leftSide = yourString.left(5);
qDebug() << leftSide; // output "This "
Also have a look at mid()
if you want more control.
when you have one certificate and 2 different web servers here how I fixed it:
In the latest version of the SDK, you would use the setBackgroundResource
method.
public void onClick(View v) {
if(v == ButtonName) {
ButtonName.setBackgroundResource(R.drawable.ImageResource);
}
}
You have to be careful while changing factors to numeric. Here is a line of code that would change a set of columns from factor to numeric. I am assuming here that the columns to be changed to numeric are 1, 3, 4 and 5 respectively. You could change it accordingly
cols = c(1, 3, 4, 5);
df[,cols] = apply(df[,cols], 2, function(x) as.numeric(as.character(x)));
You can do this with psutil which is cross-platform:
import psutil
nics = psutil.net_if_addrs()
print [j.address for j in nics[i] for i in nics if i!="lo" and j.family==17]
There are a couple generic types in .Net (v2 and later) that make passing functions around as delegates very easy.
For functions with return types, there is Func<> and for functions without return types there is Action<>.
Both Func and Action can be declared to take from 0 to 4 parameters. For example, Func < double, int > takes one double as a parameter and returns an int. Action < double, double, double > takes three doubles as parameters and returns nothing (void).
So you can declare your Diff function to take a Func:
public double Diff(double x, Func<double, double> f) {
double h = 0.0000001;
return (f(x + h) - f(x)) / h;
}
And then you call it as so, simply giving it the name of the function that fits the signature of your Func or Action:
double result = Diff(myValue, Function);
You can even write the function in-line with lambda syntax:
double result = Diff(myValue, d => Math.Sqrt(d * 3.14));
Wordpress have the checked()
function.
Reference: https://developer.wordpress.org/reference/functions/checked/
checked( mixed $checked, mixed $current = true, bool $echo = true )
Description Compares the first two arguments and if identical marks as checked
Parameters $checked (mixed) (Required) One of the values to compare
$current (mixed) (Optional) (true) The other value to compare if not just true Default value: true
$echo (bool) (Optional) Whether to echo or just return the string Default value: true
Return #Return (string) html attribute or empty string
If you use the Oracle native data provider rather than the Microsoft driver then you can get at all field types
Dim cn As New Oracle.DataAccess.Client.OracleConnection
Dim cm As New Oracle.DataAccess.Client.OracleCommand
Dim dr As Oracle.DataAccess.Client.OracleDataReader
The connection string does not require a Provider value so you would use something like:
"Data Source=myOracle;UserID=Me;Password=secret"
Open the connection:
cn.ConnectionString = "Data Source=myOracle;UserID=Me;Password=secret"
cn.Open()
Attach the command and set the Sql statement
cm.Connection = cn
cm.CommandText = strCommand
Set the Fetch size. I use 4000 because it's as big as a varchar can be
cm.InitialLONGFetchSize = 4000
Start the reader and loop through the records/columns
dr = cm.ExecuteReader
Do while dr.read()
strMyLongString = dr(i)
Loop
You can be more specific with the read, eg dr.GetOracleString(i) dr.GetOracleClob(i) etc. if you first identify the data type in the column. If you're reading a LONG datatype then the simple dr(i)
or dr.GetOracleString(i)
works fine. The key is to ensure that the InitialLONGFetchSize is big enough for the datatype. Note also that the native driver does not support CommandBehavior.SequentialAccess
for the data reader but you don't need it and also, the LONG field does not even have to be the last field in the select statement.
There is no updated
dynamic table. There is just inserted
and deleted
. On an UPDATE
command, the old data is stored in the deleted
dynamic table, and the new values are stored in the inserted
dynamic table.
Think of an UPDATE
as a DELETE/INSERT
combination.
+ The reason is: you are in the wrong directory (means it doesn't contain adb executor).
+ The solution is (step by step):
1) Find where the adb was installed. Depend on what OS you are using.
Mac, it could be in: "~/Library/Android/sdk/platform-tools
"
or
Window, it could be in: "%USERPROFILE%\AppData\Local\Android\sdk\platform-tools\
".
However, in case you could NOT remember this such long directory, you can quickly find it by the command "find
". Try this in your terminal/ command line, "find / -name "platform-tools" 2> /dev/null
" (Note: I didn't test in Window yet, but it works with Mac for sure).
*Explain the find command,
2> /dev/null
" --> ignore find results denied by permission. Try the one without this code, you will understand what I mean.2) Go to where we installed adb. There are 3 ways mentioned by many people:
Change the PATH global param (which I won't recommend) by: "export PATH=~/Library/Android/sdk/platform-tools
" which is the directory you got from above. Note, this command won't print any result, if you want to make sure you changed PATH successfully, call "export | grep PATH
" to see what the PATH is.
Add more definition for the PATH global param (which I recommend) by: "export PATH=~/Library/Android/sdk/platform-tools:$PATH
" or "export PATH=$PATH:~/Library/Android/sdk/platform-tools
"
Go to the path we found above by "cd ~/Library/Android/sdk/platform-tools
"
3) Use adb:
If you change or update the PATH, simply call any adb functions, since you added the PATH as a global param. (e.g: "adb devices
")
If you go to the PATH by cd
command, call adb functions with pre-fix "./
" (e.g: "./ adb devices
")
dt
is nullable
you need to access its Value
if (datetime.HasValue)
dt = datetime.Value;
It is important to remember that it can be NULL
. That is why the nullable
struct has the HasValue
property that tells you if it is NULL
or not.
You can also use the null-coalescing operator
??
to assign a default value
dt = datetime ?? DateTime.Now;
This will assign the value on the right if the value on the left is NULL
If you need run code after 100% loaded with image and files, test this in mounted()
:
document.onreadystatechange = () => {
if (document.readyState == "complete") {
console.log('Page completed with image and files!')
// fetch to next page or some code
}
}
More info: MDN Api onreadystatechange
On Red Hat this worked for me:
export TERM=xterm
further info here: http://www.cloudfarm.it/fix-error-opening-terminal-xterm-256color-unknown-terminal-type/
if (value == "") {
// it is empty
}
ls = [x if (condition) else None for x in ls]
According to MSDN, the JavaScript Date object does not provide any specific date formatting methods (as you may see with other programming languages). However, you can use a few of the Date
methods and formatting to accomplish your goal:
function dateToString (date) {
// Use an array to format the month numbers
var months = [
"January",
"February",
"March",
...
];
// Use an object to format the timezone identifiers
var timeZones = {
"360": "EST",
...
};
var month = months[date.getMonth()];
var day = date.getDate();
var year = date.getFullYear();
var hours = date.getHours();
var minutes = date.getMinutes();
var time = (hours > 11 ? (hours - 11) : (hours + 1)) + ":" + minutes + (hours > 11 ? "PM" : "AM");
var timezone = timeZones[date.getTimezoneOffset()];
// Returns formatted date as string (e.g. January 28, 2011 - 7:30PM EST)
return month + " " + day + ", " + year + " - " + time + " " + timezone;
}
var date = new Date("2011-01-28T19:30:00-05:00");
alert(dateToString(date));
You could even take it one step further and override the Date.toString()
method:
function dateToString () { // No date argument this time
// Use an array to format the month numbers
var months = [
"January",
"February",
"March",
...
];
// Use an object to format the timezone identifiers
var timeZones = {
"360": "EST",
...
};
var month = months[*this*.getMonth()];
var day = *this*.getDate();
var year = *this*.getFullYear();
var hours = *this*.getHours();
var minutes = *this*.getMinutes();
var time = (hours > 11 ? (hours - 11) : (hours + 1)) + ":" + minutes + (hours > 11 ? "PM" : "AM");
var timezone = timeZones[*this*.getTimezoneOffset()];
// Returns formatted date as string (e.g. January 28, 2011 - 7:30PM EST)
return month + " " + day + ", " + year + " - " + time + " " + timezone;
}
var date = new Date("2011-01-28T19:30:00-05:00");
Date.prototype.toString = dateToString;
alert(date.toString());
An alternative way:
SELECT ...
FROM bla
WHERE finalDate = (SELECT MAX(finalDate) FROM bla) AND
rownum = 1
The TypeError
is happening because k
is a list, since it is created using a slice from another list with the line k = list[0:j]
. This should probably be something like k = ' '.join(list[0:j])
, so you have a string instead.
In addition to this, your if
statement is incorrect as noted by Jesse's answer, which should read if k not in d
or if not k in d
(I prefer the latter).
You are also clearing your dictionary on each iteration since you have d = {}
inside of your for
loop.
Note that you should also not be using list
or file
as variable names, since you will be masking builtins.
Here is how I would rewrite your code:
d = {}
with open("filename.txt", "r") as input_file:
for line in input_file:
fields = line.split()
j = fields.index("x")
k = " ".join(fields[:j])
d.setdefault(k, []).append(" ".join(fields[j+1:]))
The dict.setdefault()
method above replaces the if k not in d
logic from your code.
You need to remember that CSRF token is stored in the session, so this problem can also occur due to invalid session handling. If you're working on the localhost, check e.g. if session cookie domain is set correctly (in PHP it should be empty when on localhost).
webkit2html works on Mac OS X and Linux, is quite simple to install and to use. See this tutorial.
For Windows, you can go with CutyCapt, which has similar functionality.
This should work:
SELECT age, count(age)
FROM Students
GROUP by age
If you need the id as well you could include the above as a sub query like so:
SELECT S.id, S.age, C.cnt
FROM Students S
INNER JOIN (SELECT age, count(age) as cnt
FROM Students
GROUP BY age) C ON S.age = C.age
Seems like you can't iterate through JSONArray
with a for each
. You can loop through your JSONArray
like this:
for (int i=0; i < arr.length(); i++) {
arr.getJSONObject(i);
}
Tried installing it via rpm posted in above answers, but it didn't worked. What worked instead is plain pip install
.
pip install cx_oracle
The above command installed cx_oracle=6.1
Please note that I'm using python 2.7.14 Anaconda release
and oracle 12c
.
Similar question has been asked in stackoverflow before.
See here: PHP $_SERVER['HTTP_HOST'] vs. $_SERVER['SERVER_NAME'], am I understanding the man pages correctly?
Also see this article: http://shiflett.org/blog/2006/mar/server-name-versus-http-host
Recommended using HTTP_HOST, and falling back on SERVER_NAME only if HTTP_HOST was not set. He said that SERVER_NAME could be unreliable on the server for a variety of reasons, including:
- no DNS support
- misconfigured
- behind load balancing software
The column is ambiguous because it appears in both tables you would need to specify the where (or sort) field fully such as us_music.genre or de_music.genre but you'd usually specify two tables if you were then going to join them together in some fashion. The structure your dealing with is occasionally referred to as a partitioned table although it's usually done to separate the dataset into distinct files as well rather than to just split the dataset arbitrarily. If you're in charge of the database structure and there's no good reason to partition the data then I'd build one big table with an extra "origin" field that contains a country code but you're probably doing it for legitimate performance reason. Either use a union to join the tables you're interested in http://dev.mysql.com/doc/refman/5.0/en/union.html or by using the Merge database engine http://dev.mysql.com/doc/refman/5.1/en/merge-storage-engine.html.
A column with default value:
CREATE TABLE <TableName>(
...
<ColumnName> <Type> DEFAULT <DefaultValue>
...
)
<DefaultValue>
is a placeholder for a:
(
expression )
Examples:
Count INTEGER DEFAULT 0,
LastSeen TEXT DEFAULT (datetime('now'))
This works good for me.
PID=`ps -eaf | grep syncapp | grep -v grep | awk '{print $2}'` if [[ "" != "$PID" ]]; then echo "killing $PID" kill -9 $PID fi
$(function() {
$('#sortable').sortable({
start: function(event, ui) {
var start_pos = ui.item.index();
ui.item.data('start_pos', start_pos);
},
change: function(event, ui) {
var start_pos = ui.item.data('start_pos');
var index = ui.placeholder.index();
if (start_pos < index) {
$('#sortable li:nth-child(' + index + ')').addClass('highlights');
} else {
$('#sortable li:eq(' + (index + 1) + ')').addClass('highlights');
}
},
update: function(event, ui) {
$('#sortable li').removeClass('highlights');
}
});
});
You ultimately have to decide what the null bool will represent. If null
should be false
, you can do this:
bool newBool = x.HasValue ? x.Value : false;
Or:
bool newBool = x.HasValue && x.Value;
Or:
bool newBool = x ?? false;
you can set maxlength with jquery which is very fast
jQuery(document).ready(function($){ //fire on DOM ready
setformfieldsize(jQuery('#comment'), 50, 'charsremain')
})
"abcdefgh..".IndexOf("d")
returns 3
In general returns first occurrence index, if not present returns -1
It sounds like you want to use join
, e.g.:
var text = list.join();
Here is a simple example of converting your List into Spark RDD and then converting that Spark RDD into Dataframe.
Please note that I have used Spark-shell's scala REPL to execute following code, Here sc is an instance of SparkContext which is implicitly available in Spark-shell. Hope it answer your question.
scala> val numList = List(1,2,3,4,5)
numList: List[Int] = List(1, 2, 3, 4, 5)
scala> val numRDD = sc.parallelize(numList)
numRDD: org.apache.spark.rdd.RDD[Int] = ParallelCollectionRDD[80] at parallelize at <console>:28
scala> val numDF = numRDD.toDF
numDF: org.apache.spark.sql.DataFrame = [_1: int]
scala> numDF.show
+---+
| _1|
+---+
| 1|
| 2|
| 3|
| 4|
| 5|
+---+
You are using |
(pipe) to direct the output of a command into another command. What you are looking for is &&
operator to execute the next command only if the previous one succeeded:
cp /templates/apple /templates/used && cp /templates/apple /templates/inuse && rm /templates/apple
Or
cp /templates/apple /templates/used && mv /templates/apple /templates/inuse
To summarize (non-exhaustively) bash's command operators/separators:
|
pipes (pipelines) the standard output (stdout
) of one command into the standard input of another one. Note that stderr
still goes into its default destination, whatever that happen to be.|&
pipes both stdout
and stderr
of one command into the standard input of another one. Very useful, available in bash version 4 and above.&&
executes the right-hand command of &&
only if the previous one succeeded.||
executes the right-hand command of ||
only it the previous one failed.;
executes the right-hand command of ;
always regardless whether the previous command succeeded or failed. Unless set -e
was previously invoked, which causes bash
to fail on an error.You can find the info here: http://www.php.net/manual/en/language.operators.comparison.php
It's scarce because it wasn't added until PHP4. What you have is fine though, if you know there may be a type difference then it's a much better comparison, since it's testing value and type in the comparison, not just value.
As stated in an article by Slicehost:
User setup
So let's start by adding the main user to the Apache user group:
sudo usermod -a -G www-data demo
That adds the user 'demo' to the 'www-data' group. Do ensure you use both the -a and the -G options with the usermod command shown above.
You will need to log out and log back in again to enable the group change.
Check the groups now:
groups ... # demo www-data
So now I am a member of two groups: My own (demo) and the Apache group (www-data).
Folder setup
Now we need to ensure the public_html folder is owned by the main user (demo) and is part of the Apache group (www-data).
Let's set that up:
sudo chgrp -R www-data /home/demo/public_html
As we are talking about permissions I'll add a quick note regarding the sudo command: It's a good habit to use absolute paths (/home/demo/public_html) as shown above rather than relative paths (~/public_html). It ensures sudo is being used in the correct location.
If you have a public_html folder with symlinks in place then be careful with that command as it will follow the symlinks. In those cases of a working public_html folder, change each folder by hand.
Setgid
Good so far, but remember the command we just gave only affects existing folders. What about anything new?
We can set the ownership so anything new is also in the 'www-data' group.
The first command will change the permissions for the public_html directory to include the "setgid" bit:
sudo chmod 2750 /home/demo/public_html
That will ensure that any new files are given the group 'www-data'. If you have subdirectories, you'll want to run that command for each subdirectory (this type of permission doesn't work with '-R'). Fortunately new subdirectories will be created with the 'setgid' bit set automatically.
If we need to allow write access to Apache, to an uploads directory for example, then set the permissions for that directory like so:
sudo chmod 2770 /home/demo/public_html/domain1.com/public/uploads
The permissions only need to be set once as new files will automatically be assigned the correct ownership.
header_remove("X-Powered-By");
In laymen's terms, if you use the @Transient annotation on an attribute of an entity: this attribute will be singled out and will not be saved to the database. The rest of the attribute of the object within the entity will still be saved.
Im saving the Object to the database using the jpa repository built in save method as so:
userRoleJoinRepository.save(user2);
Anaconda or Miniconda?
Choose Anaconda if you:
Are new to conda or Python.
Like the convenience of having Python and over 1,500 scientific packages automatically installed at once.
Have the time and disk space---a few minutes and 3 GB.
Do not want to individually install each of the packages you want to use.
Choose Miniconda if you:
Do not mind installing each of the packages you want to use individually.
Do not have time or disk space to install over 1,500 packages at once.
Want fast access to Python and the conda commands and you wish to sort out the other programs later.
If you're using jQuery with rails, be wary of allowing entry to methods without verifying the authenticity token.
jquery-ujs can manage the tokens for you
You should have it already as part of the jquery-rails gem, but you might need to include it in application.js with
//= require jquery_ujs
That's all you need - your ajax call should now work
For more information, see: https://github.com/rails/jquery-ujs
Here's how to do it in Squarespace using the embed block classes to create responsiveness.
Put this into a code block:
<div class="sqs-block embed-block sqs-block-embed" data-block-type="22" >
<div class="sqs-block-content"><div class="intrinsic" style="max-width:100%">
<div class="embed-block-wrapper embed-block-provider-YouTube" style="padding-bottom:56.20609%;">
<iframe allow="autoplay; fullscreen" scrolling="no" data-image-dimensions="854x480" allowfullscreen="true" src="https://www.youtube.com/embed/live_stream?channel=CHANNEL_ID_HERE" width="854" data-embed="true" frameborder="0" title="YouTube embed" class="embedly-embed" height="480">
</iframe>
</div>
</div>
</div>
Tweak however you'd like!
in my.cnf file , please change the following
## Instead of skip-networking the default is now to listen only on ## localhost which is more compatible and is not less secure. ## bind-address = 127.0.0.1
Use a Pair
as keys for the HashMap
. JDK has no Pair, but you can either use a 3rd party libraray such as http://commons.apache.org/lang or write a Pair taype of your own.
If you have control of a backend and are using django, a 4 line implementation of Dan's idea is:
def get_browser_lang(request):
if request.META.has_key('HTTP_ACCEPT_LANGUAGE'):
return JsonResponse({'response': request.META['HTTP_ACCEPT_LANGUAGE']})
else:
return JsonResponse({'response': settings.DEFAULT_LANG})
then in urls.py:
url(r'^browserlang/$', views.get_browser_lang, name='get_browser_lang'),
and on the front end:
$.get(lg('SERVER') + 'browserlang/', function(data){
var lang_code = data.response.split(',')[0].split(';')[0].split('-')[0];
});
(you have to set DEFAULT_LANG in settings.py of course)
Simple one, just do like this..
ListViewItem lvi = new ListViewItem(pet.Name);
lvi.SubItems.Add(pet.Type);
lvi.SubItems.Add(pet.Age);
listView.Items.Add(lvi);
JSON string that needs to be deserialized will have to contain the type information about parameter T
.
You will have to put Jackson annotations on every class that can be passed as parameter T
to class Data
so that the type information about parameter type T
can be read from / written to JSON string by Jackson.
Let us assume that T
can be any class that extends abstract class Result
.
class Data <T extends Result> {
int found;
Class<T> hits
}
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.WRAPPER_OBJECT)
@JsonSubTypes({
@JsonSubTypes.Type(value = ImageResult.class, name = "ImageResult"),
@JsonSubTypes.Type(value = NewsResult.class, name = "NewsResult")})
public abstract class Result {
}
public class ImageResult extends Result {
}
public class NewsResult extends Result {
}
Once each of the class (or their common supertype) that can be passed as parameter T
is annotated, Jackson will include information about parameter T
in the JSON. Such JSON can then be deserialized without knowing the parameter T
at compile time.
This Jackson documentation link talks about Polymorphic Deserialization but is useful to refer to for this question as well.
I tried using the dtypes=[datetime, ...] option, but
import pandas as pd
from datetime import datetime
headers = ['col1', 'col2', 'col3', 'col4']
dtypes = [datetime, datetime, str, float]
pd.read_csv(file, sep='\t', header=None, names=headers, dtype=dtypes)
I encountered the following error:
TypeError: data type not understood
The only change I had to make is to replace datetime with datetime.datetime
import pandas as pd
from datetime import datetime
headers = ['col1', 'col2', 'col3', 'col4']
dtypes = [datetime.datetime, datetime.datetime, str, float]
pd.read_csv(file, sep='\t', header=None, names=headers, dtype=dtypes)
Try this to get all the form fields.
var fields = document['formName'].elements;
The problem, as the Traceback says, comes from the line x[i+1] = x[i] + ( t[i+1] - t[i] ) * f( x[i], t[i] )
. Let's replace it in its context:
i + 1 >= len(x)
<=> i >= 0
, the element x[i+1]
doesn't exist. Here, this element doesn't exist since the beginning of the for loop.To solve this, you must replace x[i+1] = x[i] + ( t[i+1] - t[i] ) * f( x[i], t[i] )
by x.append(x[i] + ( t[i+1] - t[i] ) * f( x[i], t[i] ))
.
The following commands (modified after those found here) worked for me on my WSL install of Ubuntu after hours of trial and error:
sudo service mysql stop
sudo mysqld --skip-grant-tables &
mysql -u root mysql
UPDATE mysql.user SET authentication_string=null WHERE User='root';
flush privileges;
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'your_new_password_here';
flush privileges;
exit;
Of course ios7 prohibits creating fake locations on real device.
For testing purpose there are two approches:
1) while device is connected to xcode, use the simulator and let it play a gpx track.
2) for real world testing, not connected to simu, one possibility is that your app, has a special modus built in, where you set it to "playback" mode. In that mode the app has to create the locations itself, using a timer of 1s, and creating a new CLLocation object.
3) A third possibility is described here: https://blackpixel.com/writing/2013/05/simulating-locations-with-xcode.html
You can use phpseclib pollyfill package. You can not use open ssl or libsodium for encrypt/decrypt with rijndael 256. Another issue, you don't need replacement any code.
Took me a while to find this but note that if you have a spacing error you will also get the same error:
[: =: unary operator expected
Correct:
if [ "$APP_ENV" = "staging" ]
vs
if ["$APP_ENV" = "staging" ]
As always setting -x
debug variable helps to find these:
set -x
Try this
link_to "+ Service", my_services_new_path(:account_id => acct.id)
it will pass the account_id as you want.
For more details on link_to use this http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-link_to
You have a few options:
Put different URLs in the action for the two forms. Then you'll have two different view functions to deal with the two different forms.
Read the submit button values from the POST data. You can tell which submit button was clicked: How can I build multiple submit buttons django form?
From my experiences the first few frames that are captured when using:
frame = cvQueryFrame( capture );
Tend to be blank. You may want to wait a short while(about 3 seconds) and then try to capture the image.
Example
<div ng-controller="ExampleController">
<form name="myform">
Name: <input type="text" ng-model="user.name" /><br>
Email: <input type="email" ng-model="user.email" /><br>
</form>
</div>
<script>
angular.module('formExample', [])
.controller('ExampleController', ['$scope', function($scope) {
//if form is not valid then return the form.
if(!$scope.myform.$valid) {
return;
}
}]);
</script>
Once I also had a busy script which was occupied for hours without showing any progress. So I implemented a function which mainly includes the techniques of the previous answers:
#!/bin/bash
# Updates the progress bar
# Parameters: 1. Percentage value
update_progress_bar()
{
if [ $# -eq 1 ];
then
if [[ $1 == [0-9]* ]];
then
if [ $1 -ge 0 ];
then
if [ $1 -le 100 ];
then
local val=$1
local max=100
echo -n "["
for j in $(seq $max);
do
if [ $j -lt $val ];
then
echo -n "="
else
if [ $j -eq $max ];
then
echo -n "]"
else
echo -n "."
fi
fi
done
echo -ne " "$val"%\r"
if [ $val -eq $max ];
then
echo ""
fi
fi
fi
fi
fi
}
update_progress_bar 0
# Further (time intensive) actions and progress bar updates
update_progress_bar 100
Download xcode 10.2 from below link https://developer.apple.com/services-account/download?path=/Developer_Tools/Xcode_10.2/Xcode_10.2.xip
Edit: Minimum System Version* to 10.13.6 in Info.plist at below paths
Xcode.app/Contents/Info.plist
Xcode.app/Contents/Developer/Applications/Simulator.app/Contents/Info.plist
Replace: Xcode.app/Contents/Developer/usr/bin/xcodebuild
from Xcode 10
****OR*****
you can install disk image of 12.2 in your existing xcode to run on 12.2 devices Download disk image from here https://github.com/xushuduo/Xcode-iOS-Developer-Disk-Image/releases/download/12.2/12.2.16E5191d.zip
And paste at Path: /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport
Note: Restart the Xcode
I still go with the uppercase for const values, but this is more out of habit than for any particular reason.
Of course it makes it easy to see immediately that something is a const. The question to me is: Do we really need this information? Does it help us in any way to avoid errors? If I assign a value to the const, the compiler will tell me I did something dumb.
My conclusion: Go with the camel casing. Maybe I will change my style too ;-)
Edit:
That something smells hungarian is not really a valid argument, IMO. The question should always be: Does it help, or does it hurt?
There are cases when hungarian helps. Not that many nowadays, but they still exist.
in my case: 1. in IIS Manager, in left tree, left click the computer name, in right dialog click ISAPI and CGT limitation, in open dialog, select ASP.NET v4.0.30319 and select enable. There is two ASP.Net v4.0, one for 32bit, another for 64 bit. select depending on your OS bit. 2. in left tree select app pool, in right dialog, select the app pool your website used. double click that pool, in open dialog, .net framke item select .net framework v.4.0.30319. and pipe..item select integate. Maybe there is some wrong translation above because my OS is not English version.
i just want to emphasize what mwebber said in the comment:
also check if jQuery is not included twice
:)
it was the issue for me
As of CSS3, the spec has changed, allowing for only a single font-style
. A comma-separated list (per CSS2) will be treated as if it were normal
and override any earlier (default) entry. This will make fonts defined in this way appear italic permanently.
@font-face {
font-family: "DejaVu Sans";
src: url("fonts/DejaVuSans.ttf");
}
@font-face {
font-family: "DejaVu Sans";
src: url("fonts/DejaVuSans-Bold.ttf");
font-weight: bold;
}
@font-face {
font-family: "DejaVu Sans";
src: url("fonts/DejaVuSans-Oblique.ttf");
font-style: italic;
}
@font-face {
font-family: "DejaVu Sans";
src: url("fonts/DejaVuSans-BoldOblique.ttf");
font-weight: bold;
font-style: italic;
}
@font-face {
font-family: "DejaVu Sans";
src: url("fonts/DejaVuSans-Oblique.ttf");
font-style: oblique;
}
@font-face {
font-family: "DejaVu Sans";
src: url("fonts/DejaVuSans-BoldOblique.ttf");
font-weight: bold;
font-style: oblique;
}
In most cases, italic will probably be sufficient and oblique rules won't be necessary if you take care to define whichever you will use and stick to it.
I save files in .XLSB format to cut size. The XLSB also allows for VBA and macros to stay with the file. I've seen 50 meg files down to less than 10 with the Binary formatting.
You Must use
-(void)viewWillAppear:(BOOL)animated
and set your entries like you want...
It's now 2019, and the latest draft of the CSS Nesting Module actually has something like this. Introducing @nest
at-rules.
3.2. The Nesting At-Rule: @nest
While direct nesting looks nice, it is somewhat fragile. Some valid nesting selectors, like .foo &, are disallowed, and editing the selector in certain ways can make the rule invalid unexpectedly. As well, some people find the nesting challenging to distinguish visually from the surrounding declarations.
To aid in all these issues, this specification defines the @nest rule, which imposes fewer restrictions on how to validly nest style rules. Its syntax is:
@nest = @nest <selector> { <declaration-list> }
The @nest rule functions identically to a style rule: it starts with a selector, and contains declarations that apply to the elements the selector matches. The only difference is that the selector used in a @nest rule must be nest-containing, which means it contains a nesting selector in it somewhere. A list of selectors is nest-containing if all of its individual complex selectors are nest-containing.
(Copy and pasted from the URL above).
Example of valid selectors under this specification:
.foo {
color: red;
@nest & > .bar {
color: blue;
}
}
/* Equivalent to:
.foo { color: red; }
.foo > .bar { color: blue; }
*/
.foo {
color: red;
@nest .parent & {
color: blue;
}
}
/* Equivalent to:
.foo { color: red; }
.parent .foo { color: blue; }
*/
.foo {
color: red;
@nest :not(&) {
color: blue;
}
}
/* Equivalent to:
.foo { color: red; }
:not(.foo) { color: blue; }
*/
Here are a few options for changing text / label sizes
library(ggplot2)
# Example data using mtcars
a <- aggregate(mpg ~ vs + am , mtcars, function(i) round(mean(i)))
p <- ggplot(mtcars, aes(factor(vs), y=mpg, fill=factor(am))) +
geom_bar(stat="identity",position="dodge") +
geom_text(data = a, aes(label = mpg),
position = position_dodge(width=0.9), size=20)
The size
in the geom_text
changes the size of the geom_text
labels.
p <- p + theme(axis.text = element_text(size = 15)) # changes axis labels
p <- p + theme(axis.title = element_text(size = 25)) # change axis titles
p <- p + theme(text = element_text(size = 10)) # this will change all text size
# (except geom_text)
For this And why size of 10 in geom_text() is different from that in theme(text=element_text()) ?
Yes, they are different. I did a quick manual check and they appear to be in the ratio of ~ (14/5) for geom_text
sizes to theme
sizes.
So a horrible fix for uniform sizes is to scale by this ratio
geom.text.size = 7
theme.size = (14/5) * geom.text.size
ggplot(mtcars, aes(factor(vs), y=mpg, fill=factor(am))) +
geom_bar(stat="identity",position="dodge") +
geom_text(data = a, aes(label = mpg),
position = position_dodge(width=0.9), size=geom.text.size) +
theme(axis.text = element_text(size = theme.size, colour="black"))
This of course doesn't explain why? and is a pita (and i assume there is a more sensible way to do this)
Based on @balupton's answer:
$(document).on('focus', '[contenteditable]', e => {_x000D_
const self = $(e.target)_x000D_
self.data('before', self.html())_x000D_
})_x000D_
$(document).on('blur', '[contenteditable]', e => {_x000D_
const self = $(e.target)_x000D_
if (self.data('before') !== self.html()) {_x000D_
self.trigger('change')_x000D_
}_x000D_
})
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
Use the target
attribute on your anchor
tag with the _blank
value.
Example:
<a href="http://google.com" target="_blank">Click Me!</a>
You can use URL Encoding Functions PHP has the
rawurlencode()
function
ASP has the
Server.URLEncode()
function
In JavaScript you can use the
encodeURIComponent()
function.
for Python 2.7
for x in range(0, 3):
print x,
for Python 3
for x in range(0, 3):
print(x, end=" ")
If you want to find dependencies recursively (including dependencies of dependencies, dependencies of dependencies of dependencies and so on)…
You may use ldd
command.
ldd - print shared library dependencies
Now you can use https://sites.google.com
Build internal project hubs, team sites, public-facing websites, and more—all without designer, programmer, or IT help. With the new Google Sites, building websites is easy. Just drag content where you need it.
Simple tabulation of the output:
a = 0.3333333
b = 200/3
print("variable a variable b")
print("%10.2f %10.2f" % (a, b))
output:
variable a variable b
0.33 66.67
%10.2f: 10 is the minimum length and 2 is the number of decimal places.
It's very straightforward if you have an Underscore.js dependency in your project -
_.omit(myArray, "lastname")
or
A very simple method for single-line files, requiring GNU echo from coreutils:
/bin/echo -n $(cat $file)
If you really want to insert this record, remove the `abuse_id`
field and the corresponding value from the INSERT
statement :
INSERT INTO `abuses` ( `user_id` , `abuser_username` , `comment` , `reg_date` , `auction_id` )
VALUES ( 100020, 'artictundra', 'I placed a bid for it more than an hour ago. It is still active. I thought I was supposed to get an email after 15 minutes.', 1338052850, 108625 ) ;
<object CLASSID="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" width="320" height="256" CODEBASE="http://www.apple.com/qtactivex/qtplugin.cab">
<param name="src" value="sample.mov">
<param name="qtsrc" value="rtsp://realmedia.uic.edu/itl/ecampb5/demo_broad.mov">
<param name="autoplay" value="true">
<param name="loop" value="false">
<param name="controller" value="true">
<embed src="sample.mov" qtsrc="rtsp://realmedia.uic.edu/itl/ecampb5/demo_broad.mov" width="320" height="256" autoplay="true" loop="false" controller="true" pluginspage="http://www.apple.com/quicktime/"></embed>
</object>
source is the first search result of the Google
These settings worked for me:
wv.setInitialScale(1);
wv.getSettings().setLoadWithOverviewMode(true);
wv.getSettings().setUseWideViewPort(true);
wv.getSettings().setJavaScriptEnabled(true);
setInitialScale(1) was missing in my attempts.
Although documentation says that 0 will zoom all the way out if setUseWideViewPort is set to true but 0 did not work for me and I had to set 1.
Let’s try to keep this least technical.
Let’s say you are sending a html form data to node-js server i.e. you made a request to the server. The server file would receive your request under a request object. Now by logic, if you console log this request object in your server file you should see your form data some where in it, which could be extracted then, but whoa ! you actually don’t !
So, where is our data ? How will we extract it if its not only present in my request.
Simple explanation to this is http sends your form data in bits and pieces which are intended to get assembled as they reach their destination. So how would you extract your data.
But, why take this pain of every-time manually parsing your data for chunks and assembling it. Use something called “body-parser” which would do this for you.
body-parser parses your request and converts it into a format from which you can easily extract relevant information that you may need.
For example, let’s say you have a sign-up form at your frontend. You are filling it, and requesting server to save the details somewhere.
Extracting username and password from your request goes as simple as below if you use body-parser.
var loginDetails = {
username : request.body.username,
password : request.body.password
};
So basically, body-parser parsed your incoming request, assembled the chunks containing your form data, then created this body object for you and filled it with your form data.
What about iterating on the /proc virtual file system ? http://linux.die.net/man/5/proc ?
It's only blank for you because you have not set the sql_mode. If you set it, then that query will show you the details:
mysql> SELECT @@sql_mode;
+------------+
| @@sql_mode |
+------------+
| |
+------------+
1 row in set (0.00 sec)
mysql> set sql_mode=ORACLE;
Query OK, 0 rows affected (0.00 sec)
mysql> SELECT @@sql_mode;
+----------------------------------------------------------------------------------------------------------------------+
| @@sql_mode |
+----------------------------------------------------------------------------------------------------------------------+
| PIPES_AS_CONCAT,ANSI_QUOTES,IGNORE_SPACE,ORACLE,NO_KEY_OPTIONS,NO_TABLE_OPTIONS,NO_FIELD_OPTIONS,NO_AUTO_CREATE_USER |
+----------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)
Try using
$("#mydialog").closest(".ui-dialog-titlebar").hide();
This will hide all dialogs titles
$(".ui-dialog-titlebar").hide();
Although this is a old thread, I have come across the same error recently while running nslookup in CentOS 7 and google search led me to some of the discussions in SO including this one. However, adding the nameservers entries to /etc/resolv.conf alone did not help as the nameserver values in resolv.conf were overwritten by the NetworkManager with the default DNS nameservers that are in the eth profile associated to the ethernet IP config.
As mentioned by @m-canvar, set the following entries in /etc/resolv.conf
search yourdomain.com
nameserver 8.8.8.8
nameserver 4.2.2.1
nameserver 8.8.4.4
To prevent overwriting these entries by NetworkManager, there are two two approaches:
Option 1: Either set NM_CONTROLLED=no in the eth profile associated to the IPv4/IPv6 profile.
Option 2: Disable NetworkManager service from running.
chkconfig NetworkManager off
service NetworkManager stop
More details can be referred in my post about this error and solution.
This is a fairly old thread, but since I was reinstalling my Visual Studio 2015 Community today, I thought I might add some info on what to use on VS2015, or what might work in general.
To see which instances were installed by default, type sqllocaldb info
inside a command prompt. On my machine, I get two instances, the first one named MSSQLLocalDB
.
C:\>sqllocaldb info
MSSQLLocalDB
ProjectsV13
You can also create a new instance if you wish, using sqllocaldb create "some_instance_name"
, but the default one will work just fine:
// if not using a verbatim string literal, don't forget to escape backslashes
@"Server=(localdb)\MSSQLLocalDB;Integrated Security=true;"
The data in COL1 is in dd-mon-yy
No it's not. A DATE
column does not have any format. It is only converted (implicitely) to that representation by your SQL client when you display it.
If COL1 is really a DATE
column using to_date()
on it is useless because to_date()
converts a string to a DATE.
You only need to_char(), nothing else:
SELECT TO_CHAR(col1, 'mm/dd/yyyy')
FROM TABLE1
What happens in your case is that calling to_date()
converts the DATE
into a character value (applying the default NLS format) and then converting that back to a DATE. Due to this double implicit conversion some information is lost on the way.
Edit
So you did make that big mistake to store a DATE in a character column. And that's why you get the problems now.
The best (and to be honest: only sensible) solution is to convert that column to a DATE
. Then you can convert the values to any rerpresentation that you want without worrying about implicit data type conversion.
But most probably the answer is "I inherited this model, I have to cope with it" (it always is, apparently no one ever is responsible for choosing the wrong datatype), then you need to use RR
instead of YY
:
SELECT TO_CHAR(TO_DATE(COL1,'dd-mm-rr'), 'mm/dd/yyyy')
FROM TABLE1
should do the trick. Note that I also changed mon
to mm
as your example is 27-11-89
which has a number for the month, not an "word" (like NOV)
For more details see the manual: http://docs.oracle.com/cd/B28359_01/server.111/b28286/sql_elements004.htm#SQLRF00215
Many people prefer to use just .keep
since the convention has nothing to do with git.
\if what you have posted is exactly what you are using then your problem is a bit obvious. Now assuming in your web.config you have you connection string defined like this
<add name="SiteSqlServer" connectionString="Data Source=(local);Initial Catalog=some_db;User ID=sa;Password=uvx8Pytec" providerName="System.Data.SqlClient" />
In your code you should use the value in the name attribute to refer to the connection string you want (you could actually define several connection strings to different databases), so you would have
con.ConnectionString = ConfigurationManager.ConnectionStrings["SiteSqlServer"].ConnectionString;
If you are using Linux environment then you can use the PHP's exec command to invoke the linux curl. Here is a sample code, which will make a Asynchronous HTTP post.
function _async_http_post($url, $json_string) {
$run = "curl -X POST -H 'Content-Type: application/json'";
$run.= " -d '" .$json_string. "' " . "'" . $url . "'";
$run.= " > /dev/null 2>&1 &";
exec($run, $output, $exit);
return $exit == 0;
}
This code does not need any extra PHP libs and it can complete the http post in less than 10 milliseconds.
You can use lists comprehensions:
strip_list = [item.strip() for item in lines]
Or the map
function:
# with a lambda
strip_list = map(lambda it: it.strip(), lines)
# without a lambda
strip_list = map(str.strip, lines)
How are you adding your Weblogic classes to the classpath in Eclipse? Are you using WTP, and a server runtime? If so, is your server runtime associated with your project?
If you right click on your project and choose build path->configure
build path and then choose the libraries tab. You should see the weblogic libraries associated here. If you do not you can click Add Library->Server Runtime
. If the library is not there, then you first need to configure it. Windows->Preferences->Server->Installed runtimes
you can do it via normal JS also
var url = document.URL
var newAdditionalURL = "";
var tempArray = url.split("?");
var baseURL = tempArray[0];
var aditionalURL = tempArray[1];
var temp = "";
if(aditionalURL)
{
var tempArray = aditionalURL.split("&");
for ( var i in tempArray ){
if(tempArray[i].indexOf("rows") == -1){
newAdditionalURL += temp+tempArray[i];
temp = "&";
}
}
}
var rows_txt = temp+"rows=10";
var finalURL = baseURL+"?"+newAdditionalURL+rows_txt;
In my case, I wanted to check out
a new branch
that has cut recently
but it's it big in size and I want to save time and internet bandwidth, as I'm in a slow metered network
so I copped the previous branch
that I already checked in
I went to the working directory, and from svn info, I can see it's on the previous branch I did the following command (you can find this command from svn switch --help
)
svn switch ^/branches/newBranchName
go check svn info
again you can see it is becoming the newBranchName go ahead and svn up
and this how I got the new branch easily, quickly with minimum data transmitting over the internet
hope sharing my case helps and speeds up your work
I would not recommend doing such a thing. As mentioned multiple times install_requires
and requirements.txt
are definitely not supposed to be the same list. But since there are a lot of misleading answers all around involving private internal APIs of pip, it might be worth looking at saner alternatives...
There is no need for pip to parse a requirements.txt
file from a setuptools setup.py
script. The setuptools project already contains all the necessary tools in its top level package pkg_resources
.
It could more or less look like this:
#!/usr/bin/env python3
import pathlib
import pkg_resources
import setuptools
with pathlib.Path('requirements.txt').open() as requirements_txt:
install_requires = [
str(requirement)
for requirement
in pkg_resources.parse_requirements(requirements_txt)
]
setuptools.setup(
install_requires=install_requires,
)
Notes:
I fix it on my notebook. The rsyslog service did not listen on socket service.
I config this line bellow in /etc/rsyslog.conf
file and solved the problem:
$SystemLogSocketName /dev/log
Try putting this HTML snippet into your served document:
<img id="ItemPreview" src="">
Then, on JavaScript side, you can dynamically modify image's src
attribute with so-called Data URL.
document.getElementById("ItemPreview").src = "data:image/png;base64," + yourByteArrayAsBase64;
Alternatively, using jQuery:
$('#ItemPreview').attr('src', `data:image/png;base64,${yourByteArrayAsBase64}`);
This assumes that your image is stored in PNG format, which is quite popular. If you use some other image format (e.g. JPEG), modify the MIME type ("image/..."
part) in the URL accordingly.
Similar Questions:
The other answers are correct but if you're doing numerical work, you might want to consider numpy. Using numpy, the answer is:
v = numpy.diff(t)
Anytime you're changing the headers of an HttpWebRequest
, you need to use the appropriate properties on the object itself, if they exist. If you have a plain WebRequest
, be sure to cast it to an HttpWebRequest
first. Then Referrer
in your case can be accessed via ((HttpWebRequest)request).Referrer
, so you don't need to modify the header directly - just set the property to the right value. ContentLength
, ContentType
, UserAgent
, etc, all need to be set this way.
IMHO, this is a shortcoming on MS part...setting the headers via Headers.Add()
should automatically call the appropriate property behind the scenes, if that's what they want to do.
You are not comparing dates. You are comparing strings. In the world of string comparisons, 09/17/2015
> 01/02/2016
because 09
> 01
. You need to either put your date in a comparable string format or compare DateTime
objects which are comparable.
<?php
$date_now = date("Y-m-d"); // this format is string comparable
if ($date_now > '2016-01-02') {
echo 'greater than';
}else{
echo 'Less than';
}
Or
<?php
$date_now = new DateTime();
$date2 = new DateTime("01/02/2016");
if ($date_now > $date2) {
echo 'greater than';
}else{
echo 'Less than';
}
This is my solution, it's not that tricky and allow you to use it for several markup throught a simple ng-class directive. Like so you can choose the class and the scrollPos for each case.
Your App.js :
angular.module('myApp',[])
.controller('mainCtrl',function($window, $scope){
$scope.scrollPos = 0;
$window.onscroll = function(){
$scope.scrollPos = document.body.scrollTop || document.documentElement.scrollTop || 0;
$scope.$apply(); //or simply $scope.$digest();
};
});
Your index.html :
<html ng-app="myApp">
<head></head>
<body>
<section ng-controller="mainCtrl">
<p class="red" ng-class="{fix:scrollPos >= 100}">fix me when scroll is equals to 100</p>
<p class="blue" ng-class="{fix:scrollPos >= 150}">fix me when scroll is equals to 150</p>
</section>
</body>
</html>
working JSFiddle here
EDIT :
As
$apply()
is actually calling$rootScope.$digest()
you can directly use$scope.$digest()
instead of$scope.$apply()
for better performance depending on context.
Long story short :$apply()
will always work but force the$digest
on all scopes that may cause perfomance issue.
You must create a migration, where you will specify default value for a new field, since you don't want it to be null. If null is not required, simply add null=True
and create and run migration.
I've just encountered the same problem but within my own application. I didn't like the solution with copying the dll since it's not very convenient so I did some research and came up with the following programmatic solution.
Basically, before doing any connections to SQL server, you have to add the sqljdbc_auth.dll
to path.. which is easy to say:
PathHelper.appendToPath("C:\\sqljdbc_6.2\\enu\\auth\\x64");
once you know how to do it:
import java.lang.reflect.Field;
public class PathHelper {
public static void appendToPath(String dir){
String path = System.getProperty("java.library.path");
path = dir + ";" + path;
System.setProperty("java.library.path", path);
try {
final Field sysPathsField = ClassLoader.class.getDeclaredField("sys_paths");
sysPathsField.setAccessible(true);
sysPathsField.set(null, null);
}
catch (Exception ex){
throw new RuntimeException(ex);
}
}
}
Now integration authentication works like a charm :).
Credits to https://stackoverflow.com/a/21730111/1734640 for letting me figure this out.
Use ByteArrayInputStream
:
InputStream is = new ByteArrayInputStream(decodedBytes);
I found it short and simple, and can be tested in Dev Tool console itself.
$('#id option').each( (index,element)=>console.log(
index : ${index}, value : ${element.value}, text : ${element.text}) )
Ok, I don't normally answer my own questions but after a bit of tinkering, I have figured out definitively how Oracle stores the result of a DATE subtraction.
When you subtract 2 dates, the value is not a NUMBER datatype (as the Oracle 11.2 SQL Reference manual would have you believe). The internal datatype number of a DATE subtraction is 14, which is a non-documented internal datatype (NUMBER is internal datatype number 2). However, it is actually stored as 2 separate two's complement signed numbers, with the first 4 bytes used to represent the number of days and the last 4 bytes used to represent the number of seconds.
An example of a DATE subtraction resulting in a positive integer difference:
select date '2009-08-07' - date '2008-08-08' from dual;
Results in:
DATE'2009-08-07'-DATE'2008-08-08'
---------------------------------
364
select dump(date '2009-08-07' - date '2008-08-08') from dual;
DUMP(DATE'2009-08-07'-DATE'2008
-------------------------------
Typ=14 Len=8: 108,1,0,0,0,0,0,0
Recall that the result is represented as a 2 seperate two's complement signed 4 byte numbers. Since there are no decimals in this case (364 days and 0 hours exactly), the last 4 bytes are all 0s and can be ignored. For the first 4 bytes, because my CPU has a little-endian architecture, the bytes are reversed and should be read as 1,108 or 0x16c, which is decimal 364.
An example of a DATE subtraction resulting in a negative integer difference:
select date '1000-08-07' - date '2008-08-08' from dual;
Results in:
DATE'1000-08-07'-DATE'2008-08-08'
---------------------------------
-368160
select dump(date '1000-08-07' - date '2008-08-08') from dual;
DUMP(DATE'1000-08-07'-DATE'2008-08-0
------------------------------------
Typ=14 Len=8: 224,97,250,255,0,0,0,0
Again, since I am using a little-endian machine, the bytes are reversed and should be read as 255,250,97,224 which corresponds to 11111111 11111010 01100001 11011111. Now since this is in two's complement signed binary numeral encoding, we know that the number is negative because the leftmost binary digit is a 1. To convert this into a decimal number we would have to reverse the 2's complement (subtract 1 then do the one's complement) resulting in: 00000000 00000101 10011110 00100000 which equals -368160 as suspected.
An example of a DATE subtraction resulting in a decimal difference:
select to_date('08/AUG/2004 14:00:00', 'DD/MON/YYYY HH24:MI:SS'
- to_date('08/AUG/2004 8:00:00', 'DD/MON/YYYY HH24:MI:SS') from dual;
TO_DATE('08/AUG/200414:00:00','DD/MON/YYYYHH24:MI:SS')-TO_DATE('08/AUG/20048:00:
--------------------------------------------------------------------------------
.25
The difference between those 2 dates is 0.25 days or 6 hours.
select dump(to_date('08/AUG/2004 14:00:00', 'DD/MON/YYYY HH24:MI:SS')
- to_date('08/AUG/2004 8:00:00', 'DD/MON/YYYY HH24:MI:SS')) from dual;
DUMP(TO_DATE('08/AUG/200414:00:
-------------------------------
Typ=14 Len=8: 0,0,0,0,96,84,0,0
Now this time, since the difference is 0 days and 6 hours, it is expected that the first 4 bytes are 0. For the last 4 bytes, we can reverse them (because CPU is little-endian) and get 84,96 = 01010100 01100000 base 2 = 21600 in decimal. Converting 21600 seconds to hours gives you 6 hours which is the difference which we expected.
Hope this helps anyone who was wondering how a DATE subtraction is actually stored.
You get the syntax error because the date math does not return a NUMBER, but it returns an INTERVAL:
SQL> SELECT DUMP(SYSDATE - start_date) from test;
DUMP(SYSDATE-START_DATE)
--------------------------------------
Typ=14 Len=8: 188,10,0,0,223,65,1,0
You need to convert the number in your example into an INTERVAL first using the NUMTODSINTERVAL Function
For example:
SQL> SELECT (SYSDATE - start_date) DAY(5) TO SECOND from test;
(SYSDATE-START_DATE)DAY(5)TOSECOND
----------------------------------
+02748 22:50:04.000000
SQL> SELECT (SYSDATE - start_date) from test;
(SYSDATE-START_DATE)
--------------------
2748.9515
SQL> select NUMTODSINTERVAL(2748.9515, 'day') from dual;
NUMTODSINTERVAL(2748.9515,'DAY')
--------------------------------
+000002748 22:50:09.600000000
SQL>
Based on the reverse cast with the NUMTODSINTERVAL() function, it appears some rounding is lost in translation.
Simple way is to reset the index of the DataFrame prior to filtering:
df_reset = df.reset_index()
df_reset[df_reset['BoolCol']].index.tolist()
Bit hacky, but it's quick!
The implicit join ANSI syntax is older, less obvious, and not recommended.
In addition, the relational algebra allows interchangeability of the predicates in the WHERE
clause and the INNER JOIN
, so even INNER JOIN
queries with WHERE
clauses can have the predicates rearranged by the optimizer.
I recommend you write the queries in the most readable way possible.
Sometimes this includes making the INNER JOIN
relatively "incomplete" and putting some of the criteria in the WHERE
simply to make the lists of filtering criteria more easily maintainable.
For example, instead of:
SELECT *
FROM Customers c
INNER JOIN CustomerAccounts ca
ON ca.CustomerID = c.CustomerID
AND c.State = 'NY'
INNER JOIN Accounts a
ON ca.AccountID = a.AccountID
AND a.Status = 1
Write:
SELECT *
FROM Customers c
INNER JOIN CustomerAccounts ca
ON ca.CustomerID = c.CustomerID
INNER JOIN Accounts a
ON ca.AccountID = a.AccountID
WHERE c.State = 'NY'
AND a.Status = 1
But it depends, of course.
This should be able to set to whatever keybindings you want for indent/outdent here:
Menu File → Preferences → Keyboard Shortcuts
editor.action.indentLines
editor.action.outdentLines
Following steps solved the issue for me.
This might work for you:
sed 's|$ROOT|'"${HOME}"'|g' abc.sh > abc.sh.1
This version is 26% shorter than yours but functions identically, even for redundant/ambiguous values (returns the first match, as yours does). However, it is probably twice as slow as yours, because it creates a list from the dict twice.
key = dict_obj.keys()[dict_obj.values().index(value)]
Or if you prefer brevity over readability you can save one more character with
key = list(dict_obj)[dict_obj.values().index(value)]
And if you prefer efficiency, @PaulMcGuire's approach is better. If there are lots of keys that share the same value it's more efficient not to instantiate that list of keys with a list comprehension and instead use use a generator:
key = (key for key, value in dict_obj.items() if value == 'value').next()
Another (less javascriptish) approach, that I did, goes something like this:
public static MvcHtmlString AntiForgeryTokenForAjaxPost(this HtmlHelper helper)
{
var antiForgeryInputTag = helper.AntiForgeryToken().ToString();
// Above gets the following: <input name="__RequestVerificationToken" type="hidden" value="PnQE7R0MIBBAzC7SqtVvwrJpGbRvPgzWHo5dSyoSaZoabRjf9pCyzjujYBU_qKDJmwIOiPRDwBV1TNVdXFVgzAvN9_l2yt9-nf4Owif0qIDz7WRAmydVPIm6_pmJAI--wvvFQO7g0VvoFArFtAR2v6Ch1wmXCZ89v0-lNOGZLZc1" />
var removedStart = antiForgeryInputTag.Replace(@"<input name=""__RequestVerificationToken"" type=""hidden"" value=""", "");
var tokenValue = removedStart.Replace(@""" />", "");
if (antiForgeryInputTag == removedStart || removedStart == tokenValue)
throw new InvalidOperationException("Oops! The Html.AntiForgeryToken() method seems to return something I did not expect.");
return new MvcHtmlString(string.Format(@"{0}:""{1}""", "__RequestVerificationToken", tokenValue));
}
__RequestVerificationToken:"P5g2D8vRyE3aBn7qQKfVVVAsQc853s-naENvpUAPZLipuw0pa_ffBf9cINzFgIRPwsf7Ykjt46ttJy5ox5r3mzpqvmgNYdnKc1125jphQV0NnM5nGFtcXXqoY3RpusTH_WcHPzH4S4l1PmB8Uu7ubZBftqFdxCLC5n-xT0fHcAY1"
$(function () {
$("#submit-list").click(function () {
$.ajax({
url: '@Url.Action("SortDataSourceLibraries")',
data: { items: $(".sortable").sortable('toArray'), @Html.AntiForgeryTokenForAjaxPost() },
type: 'post',
traditional: true
});
});
});
And it seems to work!
Eureka ! Finally I found a solution on this.
This is caused by Windows update that stops any 32-bit processes from consuming more than 1200 MB on a 64-bit machine. The only way you can repair this is by using the System Restore option on Win 7.
Start >> All Programs >> Accessories >> System Tools >> System Restore.
And then restore to a date on which your Java worked fine. This worked for me. What is surprising here is Windows still pushes system updates under the name of "Critical Updates" even when you disable all windows updates. ^&%)#* Windows :-)
This happened to me after I renamed a file. For some reason it was still looking for the file with the old name. What I did was create the file that it was complaining about and added to the project. Then I did a Project->clean, then Project->Build and verified the error was gone. Then I selected the newly added files and deleted them. This removed all references and I no longer see the error.
From the documentation:
In order to execute a command and have it not hang your PHP script while
it runs, the program you run must not output back to PHP. To do this,
redirect both stdout and stderr to /dev/null, then background it.
> /dev/null 2>&1 &
In order to execute a command and have
it spawned off as another process that
is not dependent on the Apache thread
to keep running (will not die if
somebody cancels the page) run this:
exec('bash -c "exec nohup setsid your_command > /dev/null 2>&1 &"');
I had the same question as you but I wanted to kill the gnome terminal which I was in. I read the manual on "who" and found that you can list all of the sessions logged into your computer with the '-a' option and then the '-l' option prints the system login processes.
who -la
You should get something like this. Then all you have to do is kill the process with the 'kill' command.
kill <PID>
If you have a flash FLA file that shows the FLV movie you can add a button inside the FLA file. This button can be given an action to load the URL.
on (release) {
getURL("http://someurl/");
}
To make the button transparent you can place a square inside it that is moved to the hit-area frame of the button.
I think it would go too far to explain into depth with pictures how to go about in stackoverflow.
git rebase -i HEAD~<quantity of your commits>
(i.e. git rebase -i HEAD~5
)txt
file change pick
keyword to squash
for all commits, except first commit (which is on the top). For top one change it to reword
(which means you will provide a new comment for this commit in the next step) and click SAVE! If in vim, press esc
then save by entering wq!
and press enter.Done
You need to use df.shift
here.
df.shift(i)
shifts the entire dataframe by i
units down.
So, for i = 1
:
Input:
x1 x2
0 206 214
1 226 234
2 245 253
3 265 272
4 283 291
Output:
x1 x2
0 Nan Nan
1 206 214
2 226 234
3 245 253
4 265 272
So, run this script to get the expected output:
import pandas as pd
df = pd.DataFrame({'x1': ['206', '226', '245',' 265', '283'],
'x2': ['214', '234', '253', '272', '291']})
print(df)
df['x2'] = df['x2'].shift(1)
print(df)
Another approach is to use the . (dot
) command in combination with I.
vendor_
)I find this technique is often faster than the visual block mode for small numbers of additions and has the added benefit that if you don't need to insert the text on every single line in a range you can easily skip them by pressing extra j's.
Note that for large number of contiguous additions, the block approach or macro will likely be superior.
Remove the space or empty line in server.xml or context.xml at the beginning of your code
You can't. Variables defined inside a method are local to that method.
If you want to share variables between methods, then you'll need to specify them as member variables of the class. Alternatively, you can pass them from one method to another as arguments (this isn't always applicable).
Looks like you're using instance methods instead of static ones.
If you don't want to create an object, you should declare all your methods static, so something like
private static void methodName(Argument args...)
If you want a variable to be accessible by all these methods, you should initialise it outside the methods and to limit its scope, declare it private.
private static int[][] array = new int[3][5];
Global variables are usually looked down upon (especially for situations like your one) because in a large-scale program they can wreak havoc, so making it private will prevent some problems at the least.
Also, I'll say the usual: You should try to keep your code a bit tidy. Use descriptive class, method and variable names and keep your code neat (with proper indentation, linebreaks etc.) and consistent.
Here's a final (shortened) example of what your code should be like:
public class Test3 {
//Use this array in your methods
private static int[][] scores = new int[3][5];
/* Rather than just "Scores" name it so people know what
* to expect
*/
private static void createScores() {
//Code...
}
//Other methods...
/* Since you're now using static methods, you don't
* have to initialise an object and call its methods.
*/
public static void main(String[] args){
createScores();
MD(); //Don't know what these do
sumD(); //so I'll leave them.
}
}
Ideally, since you're using an array, you would create the array in the main method and pass it as an argument across each method, but explaining how that works is probably a whole new question on its own so I'll leave it at that.
Run Visual Studio as Administrator and put your SQL SERVER authentication login (who has the permission to create a DB) and password in the connection string, it worked for me
Try this,
x in mylist
is better and more readable than x in mylist[:]
and your len(x)
should be equal to 3
.
>>> mylist = [[1,2,3],[4,5,6,7],[8,9,10]]
>>> for x in mylist:
... if len(x)==3:
... print x
...
[1, 2, 3]
[8, 9, 10]
or if you need more pythonic use list-comprehensions
>>> [x for x in mylist if len(x)==3]
[[1, 2, 3], [8, 9, 10]]
>>>
Try this method. It's very easy:
public static boolean setSsidAndPassword(Context context, String ssid, String ssidPassword) {
try {
WifiManager wifiManager = (WifiManager) context.getSystemService(context.WIFI_SERVICE);
Method getConfigMethod = wifiManager.getClass().getMethod("getWifiApConfiguration");
WifiConfiguration wifiConfig = (WifiConfiguration) getConfigMethod.invoke(wifiManager);
wifiConfig.SSID = ssid;
wifiConfig.preSharedKey = ssidPassword;
Method setConfigMethod = wifiManager.getClass().getMethod("setWifiApConfiguration", WifiConfiguration.class);
setConfigMethod.invoke(wifiManager, wifiConfig);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
My guess is that the directory ~/bin/sbt/bin is not in your PATH.
To execute programs or scripts that are in the current directory you need to prefix the command with ./, as in:
./sbt
This is a security feature in linux, so to prevent overriding of system commands (and other programs) by a malicious party dropping a file in your home directory (for example). Imagine a script called 'ls' that emails your /etc/passwd file to 3rd party before executing the ls command... Or one that executes 'rm -rf .'...
That said, unless you need something specific from the latest source code, you're best off doing what paradigmatic said in his post, and install it from the Typesafe repository.
You need to set more fields then just border-width. The style basically puts the border on the page. Width controls the thickness, and color tells it what color to make the border.
border-style: solid; border-width:thin; border-color: #FFFFFF;
You could also use Except(produces the set difference of two sequences) to check whether there's a difference or not:
IEnumerable<string> inFirstOnly = a1.Except(a2);
IEnumerable<string> inSecondOnly = a2.Except(a1);
bool allInBoth = !inFirstOnly.Any() && !inSecondOnly.Any();
So this is an efficient way if the order and if the number of duplicates does not matter(as opposed to the accepted answer's SequenceEqual
). Demo: Ideone
If you want to compare in a case insentive way, just add StringComparer.OrdinalIgnoreCase
:
a1.Except(a2, StringComparer.OrdinalIgnoreCase)
It's doable but you have to know that using offset()
sets the position of the element relative to the document:
$('.layer1').offset( $('.layer2').offset() );
Quick Perl version with trailing slash handling:
ls -1 | perl -E 'say join ", ", map {chomp; $_} <>'
To explain:
javax.ws.rs.core.MediaType
from JAX-RS
This is just a sample code, but it may help you get on your way:
Public Sub testIt()
Workbooks("Workbook2").Activate
ActiveWorkbook.Sheets("Sheet2").Activate
ActiveSheet.Range("B3").Select
ActiveCell.EntireRow.Insert
End Sub
I am assuming that you can open the book (called Workbook2
in the example).
I think (but I'm not sure) you can squash all this in a single line of code:
Workbooks("Workbook2").Sheets("Sheet2").Range("B3").EntireRow.Insert
This way you won't need to activate the workbook (or sheet or cell)... Obviously, the book has to be open.
When you install third-party extensions you need to make sure that all the compilation parameters match:
Common glitches includes:
php.ini
file (that's typical with bundles); the right path is shown in phpinfo()
.Not being able to see the startup errors; those should show up in Apache logs, but you can also use the command line to diagnose it, e.g.:
php -d display_startup_errors=1 -d error_reporting=-1 -d display_errors -c "C:\Path\To\php.ini" -m
If everything's right you should see sqlsrv
in the command output and/or phpinfo()
(depending on what SAPI you're configuring):
[PHP Modules]
bcmath
calendar
Core
[...]
SPL
sqlsrv
standard
[...]
Since pandas 1.0 it became much more straightforward. This will read column 'ID' as dtype 'string':
pd.read_csv('sample.csv',dtype={'ID':'string'})
As we can see in this Getting started guide, 'string' dtype has been introduced (before strings were treated as dtype 'object').
Yes, for scalar values, a combination of implode and array_slice will do:
$bar = implode(array_slice($array, 0, 1));
$bin = implode(array_slice($array, 1, 1));
$ipsum = implode(array_slice($array, 2, 1));
Or mix it up with array_values
and list
(thanks @nikic) so that it works with all types of values:
list($bar) = array_values(array_slice($array, 0, 1));
You can expose the service in two different endpoints. the SOAP one can use the binding that support SOAP e.g. basicHttpBinding, the RESTful one can use the webHttpBinding. I assume your REST service will be in JSON, in that case, you need to configure the two endpoints with the following behaviour configuration
<endpointBehaviors>
<behavior name="jsonBehavior">
<enableWebScript/>
</behavior>
</endpointBehaviors>
An example of endpoint configuration in your scenario is
<services>
<service name="TestService">
<endpoint address="soap" binding="basicHttpBinding" contract="ITestService"/>
<endpoint address="json" binding="webHttpBinding" behaviorConfiguration="jsonBehavior" contract="ITestService"/>
</service>
</services>
so, the service will be available at
Apply [WebGet] to the operation contract to make it RESTful. e.g.
public interface ITestService
{
[OperationContract]
[WebGet]
string HelloWorld(string text)
}
Note, if the REST service is not in JSON, parameters of the operations can not contain complex type.
For plain old XML as return format, this is an example that would work both for SOAP and XML.
[ServiceContract(Namespace = "http://test")]
public interface ITestService
{
[OperationContract]
[WebGet(UriTemplate = "accounts/{id}")]
Account[] GetAccount(string id);
}
POX behavior for REST Plain Old XML
<behavior name="poxBehavior">
<webHttp/>
</behavior>
Endpoints
<services>
<service name="TestService">
<endpoint address="soap" binding="basicHttpBinding" contract="ITestService"/>
<endpoint address="xml" binding="webHttpBinding" behaviorConfiguration="poxBehavior" contract="ITestService"/>
</service>
</services>
Service will be available at
REST request try it in browser,
SOAP request client endpoint configuration for SOAP service after adding the service reference,
<client>
<endpoint address="http://www.example.com/soap" binding="basicHttpBinding"
contract="ITestService" name="BasicHttpBinding_ITestService" />
</client>
in C#
TestServiceClient client = new TestServiceClient();
client.GetAccount("A123");
Another way of doing it is to expose two different service contract and each one with specific configuration. This may generate some duplicates at code level, however at the end of the day, you want to make it working.
There are really two separate issues. The first is keeping the elements of the array in proper order so that there are no "holes" after removing an element. The second is actually resizing the array itself.
Arrays in C are allocated as a fixed number of contiguous elements. There is no way to actually remove the memory used by an individual element in the array but the elements can be shifted to fill the hole made by removing an element. For example:
void remove_element(array_type *array, int index, int array_length)
{
int i;
for(i = index; i < array_length - 1; i++) array[i] = array[i + 1];
}
Statically allocated arrays can not be resized. Dynamically allocated arrays can be resized with realloc(). This will potentially move the entire array to another location in memory, so all pointers to the array or to its elements will have to be updated. For example:
remove_element(array, index, array_length); /* First shift the elements, then reallocate */
array_type *tmp = realloc(array, (array_length - 1) * sizeof(array_type) );
if (tmp == NULL && array_length > 1) {
/* No memory available */
exit(EXIT_FAILURE);
}
array_length = array_length - 1;
array = tmp;
realloc will return a NULL pointer if the requested size is 0, or if there is an error. Otherwise it returns a pointer to the reallocated array. The temporary pointer is used to detect errors when calling realloc because instead of exiting it is also possible to just leave the original array as it was. When realloc fails to reallocate an array it does not alter the original array.
Note that both of these operations will be fairly slow if the array is large or if a lot of elements are removed. There are other data structures like linked lists and hashes that can be used if efficient insertion and deletion is a priority.
The syntax has changed in that print
is now a function. This means that the %
formatting needs to be done inside the parenthesis:1
print("%d. %s appears %d times." % (i, key, wordBank[key]))
However, since you are using Python 3.x., you should actually be using the newer str.format
method:
print("{}. {} appears {} times.".format(i, key, wordBank[key]))
Though %
formatting is not officially deprecated (yet), it is discouraged in favor of str.format
and will most likely be removed from the language in a coming version (Python 4 maybe?).
1Just a minor note: %d
is the format specifier for integers, not %s
.
Maybe another quick solution could be:
>>> float("%.1f" % 1.00001)
1.0
>>> float("%.3f" % 1.23001)
1.23
>>> float("%.5f" % 1.23001)
1.23001
Try this code
.button:after {
content: ""
position: absolute
width: 70px
background-image: url('../../images/frontapp/mid-icon.svg')
display: inline-block
background-size: contain
background-repeat: no-repeat
right: 0
bottom: 0
}
The method for reversing a linked list is as below;
public void reverseList() {
Node<E> curr = head;
Node<E> pre = null;
Node<E> incoming = null;
while(curr != null) {
incoming = curr.next; // store incoming item
curr.next = pre; // swap nodes
pre = curr; // increment also pre
curr = incoming; // increment current
}
head = pre; // pre is the latest item where
// curr is null
}
Three references are needed to reverse a list: pre, curr, incoming
... pre curr incoming
... --> (n-1) --> (n) --> (n+1) --> ...
To reverse a node, you have to store previous element, so that you can use the simple stament;
curr.next = pre;
To reverse the current element's direction. However, to iterate over the list, you have to store incoming element before the execution of the statement above because as reversing the current element's next reference, you don't know the incoming element anymore, that's why a third reference needed.
The demo code is as below;
public class LinkedList<E> {
protected Node<E> head;
public LinkedList() {
head = null;
}
public LinkedList(E[] list) {
this();
addAll(list);
}
public void addAll(E[] list) {
for(int i = 0; i < list.length; i++)
add(list[i]);
}
public void add(E e) {
if(head == null)
head = new Node<E>(e);
else {
Node<E> temp = head;
while(temp.next != null)
temp = temp.next;
temp.next = new Node<E>(e);
}
}
public void reverseList() {
Node<E> curr = head;
Node<E> pre = null;
Node<E> incoming = null;
while(curr != null) {
incoming = curr.next; // store incoming item
curr.next = pre; // swap nodes
pre = curr; // increment also pre
curr = incoming; // increment current
}
head = pre; // pre is the latest item where
// curr is null
}
public void printList() {
Node<E> temp = head;
System.out.print("List: ");
while(temp != null) {
System.out.print(temp + " ");
temp = temp.next;
}
System.out.println();
}
public static class Node<E> {
protected E e;
protected Node<E> next;
public Node(E e) {
this.e = e;
this.next = null;
}
@Override
public String toString() {
return e.toString();
}
}
}
public class ReverseLinkedList {
public static void main(String[] args) {
Integer[] list = { 4, 3, 2, 1 };
LinkedList<Integer> linkedList = new LinkedList<Integer>(list);
linkedList.printList();
linkedList.reverseList();
linkedList.printList();
}
}
List: 4 3 2 1
List: 1 2 3 4
I think best approach is xian's answer.
but...
This approach is dirty, but can solve at all version.
so, I often use it in macro functions.
for(int _int=0, /* make local variable */ \
loopOnce=true; loopOnce==true; loopOnce=false)
for(char _char=0; _char<3; _char++)
{
// do anything with
// _int, _char
}
It can also be used to declare local variables
and initialize global variables
.
float globalFloat;
for(int localInt=0, /* decalre local variable */ \
_=1;_;_=0)
for(globalFloat=2.f; localInt<3; localInt++) /* initialize global variable */
{
// do.
}
Good example : with macro function.
(If best approach can't be used because it is a for-loop-macro)
#define for_two_decl(_decl_1, _decl_2, cond, incr) \
for(_decl_1, _=1;_;_=0)\
for(_decl_2; (cond); (incr))
for_two_decl(int i=0, char c=0, i<3, i++)
{
// your body with
// i, c
}
if (A* a=nullptr);
else
for(...) // a is visible
If you want initialize to 0
or nullptr
, you can use this trick.
but I don't recommend this because of hard reading.
and it seems like bug.
No, there isn't.
I'm pretty sure there is no way to intercept a click on the refresh button from JS, and even if there was, JS can be turned off.
You should probably step back from your X (preventing refreshing) and find a different solution to Y (whatever that might be).
Sorry for late reply but still felt like posting my answer if it helps.It works for 6 digits OTP.
@Override
public void onOTPReceived(String messageBody)
{
Pattern pattern = Pattern.compile(SMSReceiver.OTP_REGEX);
Matcher matcher = pattern.matcher(messageBody);
String otp = HkpConstants.EMPTY;
while (matcher.find())
{
otp = matcher.group();
}
checkAndSetOTP(otp);
}
Adding constants here
public static final String OTP_REGEX = "[0-9]{1,6}";
For SMS listener one can follow the below class
public class SMSReceiver extends BroadcastReceiver
{
public static final String SMS_BUNDLE = "pdus";
public static final String OTP_REGEX = "[0-9]{1,6}";
private static final String FORMAT = "format";
private OnOTPSMSReceivedListener otpSMSListener;
public SMSReceiver(OnOTPSMSReceivedListener listener)
{
otpSMSListener = listener;
}
@Override
public void onReceive(Context context, Intent intent)
{
Bundle intentExtras = intent.getExtras();
if (intentExtras != null)
{
Object[] sms_bundle = (Object[]) intentExtras.get(SMS_BUNDLE);
String format = intent.getStringExtra(FORMAT);
if (sms_bundle != null)
{
otpSMSListener.onOTPSMSReceived(format, sms_bundle);
}
else {
// do nothing
}
}
}
@FunctionalInterface
public interface OnOTPSMSReceivedListener
{
void onOTPSMSReceived(@Nullable String format, Object... smsBundle);
}
}
@Override
public void onOTPSMSReceived(@Nullable String format, Object... smsBundle)
{
for (Object aSmsBundle : smsBundle)
{
SmsMessage smsMessage = getIncomingMessage(format, aSmsBundle);
String sender = smsMessage.getDisplayOriginatingAddress();
if (sender.toLowerCase().contains(ONEMG))
{
getIncomingMessage(smsMessage.getMessageBody());
} else
{
// do nothing
}
}
}
private SmsMessage getIncomingMessage(@Nullable String format, Object aObject)
{
SmsMessage currentSMS;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && format != null)
{
currentSMS = SmsMessage.createFromPdu((byte[]) aObject, format);
} else
{
currentSMS = SmsMessage.createFromPdu((byte[]) aObject);
}
return currentSMS;
}
Simplified solution for adding linked servers
First server
EXEC sp_addlinkedserver @server='ip,port\instancename'
Second Login
EXEC sp_addlinkedsrvlogin 'ip,port\instancename', 'false', NULL, 'remote_db_loginname', 'remote_db_pass'
Execute queries from linked to local db
INSERT INTO Tbl (Col1, Col2, Col3)
SELECT Col1, Col2, Col3
FROM [ip,port\instancename].[linkedDBName].[linkedTblSchema].[linkedTblName]
Simple answer NO.
However you can achieve something similar by running the following version using bind variables:
SELECT * FROM Employees WHERE EmployeeID = :EmpIDVar
Once you run the query above in SQL Developer you will be prompted to enter value for the bind variable EmployeeID.
I would simply try reinstalling XAMPP.
If I understand correctly it appears you want to run the jars in a separate process from inside your java GUI application.
To do this you can use:
// Run a java app in a separate system process
Process proc = Runtime.getRuntime().exec("java -jar A.jar");
// Then retreive the process output
InputStream in = proc.getInputStream();
InputStream err = proc.getErrorStream();
Its always good practice to buffer the output of the process.
I think developers can do this for their own apps via iTunes Connect but this doesn't help you if you are looking for stats on other peoples apps.
148Apps also have some aggregate AppStore metrics on their web site that could be useful to you but, again, doesn't really give a low-level breakdown of numbers.
You could also scrape some stats from the RSS feeds generated by the iTunes Store RSS Generator but, again, this just gets currently popular apps rather than actual download numbers.
List<Person> roster = ...;
Map<String, Person> map =
roster
.stream()
.collect(
Collectors.toMap(p -> p.getLast(), p -> p)
);
that would be the translation, but i havent run this or used the API. most likely you can substitute p -> p, for Function.identity(). and statically import toMap(...)
You can optionally overload the = operator for the variable and can put the breakpoint inside the overloaded function on specific condition.
if (StartDate < EndDate)
// code
if you just want the dates, and not the time
if (StartDate.Date < EndDate.Date)
// code
LATERAL
join?The feature was introduced with PostgreSQL 9.3.
Quoting the manual:
Subqueries appearing in
FROM
can be preceded by the key wordLATERAL
. This allows them to reference columns provided by precedingFROM
items. (WithoutLATERAL
, each subquery is evaluated independently and so cannot cross-reference any otherFROM
item.)Table functions appearing in
FROM
can also be preceded by the key wordLATERAL
, but for functions the key word is optional; the function's arguments can contain references to columns provided by precedingFROM
items in any case.
Basic code examples are given there.
A LATERAL
join is more like a correlated subquery, not a plain subquery, in that expressions to the right of a LATERAL
join are evaluated once for each row left of it - just like a correlated subquery - while a plain subquery (table expression) is evaluated once only. (The query planner has ways to optimize performance for either, though.)
Related answer with code examples for both side by side, solving the same problem:
For returning more than one column, a LATERAL
join is typically simpler, cleaner and faster.
Also, remember that the equivalent of a correlated subquery is LEFT JOIN LATERAL ... ON true
:
There are things that a LATERAL
join can do, but a (correlated) subquery cannot (easily). A correlated subquery can only return a single value, not multiple columns and not multiple rows - with the exception of bare function calls (which multiply result rows if they return multiple rows). But even certain set-returning functions are only allowed in the FROM
clause. Like unnest()
with multiple parameters in Postgres 9.4 or later. The manual:
This is only allowed in the
FROM
clause;
So this works, but cannot (easily) be replaced with a subquery:
CREATE TABLE tbl (a1 int[], a2 int[]);
SELECT * FROM tbl, unnest(a1, a2) u(elem1, elem2); -- implicit LATERAL
The comma (,
) in the FROM
clause is short notation for CROSS JOIN
.
LATERAL
is assumed automatically for table functions.
About the special case of UNNEST( array_expression [, ... ] )
:
SELECT
listYou can also use set-returning functions like unnest()
in the SELECT
list directly. This used to exhibit surprising behavior with more than one such function in the same SELECT
list up to Postgres 9.6. But it has finally been sanitized with Postgres 10 and is a valid alternative now (even if not standard SQL). See:
Building on above example:
SELECT *, unnest(a1) AS elem1, unnest(a2) AS elem2
FROM tbl;
Comparison:
dbfiddle for pg 9.6 here
dbfiddle for pg 10 here
For the
INNER
andOUTER
join types, a join condition must be specified, namely exactly one ofNATURAL
,ON
join_condition, orUSING
(join_column [, ...]). See below for the meaning.
ForCROSS JOIN
, none of these clauses can appear.
So these two queries are valid (even if not particularly useful):
SELECT *
FROM tbl t
LEFT JOIN LATERAL (SELECT * FROM b WHERE b.t_id = t.t_id) t ON TRUE;
SELECT *
FROM tbl t, LATERAL (SELECT * FROM b WHERE b.t_id = t.t_id) t;
While this one is not:
SELECT *
FROM tbl t
LEFT JOIN LATERAL (SELECT * FROM b WHERE b.t_id = t.t_id) t;
That's why Andomar's code example is correct (the CROSS JOIN
does not require a join condition) and Attila's is was not.
I'm not sure how you think you can do it other than character-by-character -- it's inherently a character-by-character operation. There is certainly code out there to do this for you, but there is no "simpler" way than doing it character-by-character.
First, you need to strip the 0b
prefix, and left-zero-pad the string so it's length is divisible by 8, to make dividing the bitstring up into characters easy:
bitstring = bitstring[2:]
bitstring = -len(bitstring) % 8 * '0' + bitstring
Then you divide the string up into blocks of eight binary digits, convert them to ASCII characters, and join them back into a string:
string_blocks = (bitstring[i:i+8] for i in range(0, len(bitstring), 8))
string = ''.join(chr(int(char, 2)) for char in string_blocks)
If you actually want to treat it as a number, you still have to account for the fact that the leftmost character will be at most seven digits long if you want to go left-to-right instead of right-to-left.
OuterClass.this
references the outer class.