id
stringlengths 5
11
| text
stringlengths 0
146k
| title
stringclasses 1
value |
|---|---|---|
doc_23526200
|
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"><meta name="HandheldFriendly" content="true">
and the css content is
@media screen and (max-width: 320px) {
html, body, main {font-size: 0.88em; width: 100%;}
#firstside: {width: 100%; float:left; position: relative; margin-top: 20px; padding-left: 1%; clear: both;}
#second2 {width: 100%; float:left; margin: 2%;}
}
I know it is the wrong way around that I should have started with the mobile but I inherited the website and now need to get it mobile responsive. Can anyone help?
| |
doc_23526201
|
The error message when attempting to uninstall SQL Server 2014 is:
SQL Server Setup has encountered the following error: '.', hexadecimal
value 0x00, is an invalid character. Line 1, position 212550. Error
code 0x84B10001.
The proposed fix for this issue is to uninstall MSDE. Unfortunately I cannot uninstall MSDE either. If I try to remove it via Control Panel, after clicking the UAC prompt, the dialog closes and nothing happens.
I found this page that claims to show how to remove MSDE manually if it won't install from Control Panel:
However none of this works either. The registry entries don't exist, so I cannot determine the product code from them, so I can't use MSIZAP.EXE. I managed to delete the files under Program Files as directed, and removed the registry entries for the services, but this does not fix the issue - Microsoft SQL Server Desktop Engine (SQL2000) is still list on Programs and Features on Control Panel, and I still can't uninstall SQL Server 2014.
I have attempted to install SSMS 17.3 only, but install fails with error code 0x80070643.
I think all I can do at this point is wipe my laptop and reinstall Windows 10 from scratch if I can't solve this.
| |
doc_23526202
|
name | type
total_price | decimal(15,4)
If data is 999 record is 999.0000 that fine but if data is 1 000 (with space) record is 1
how can i fix this ?
I look at http://php.net/manual/en/function.number-format.php but didnt find anything
A: Try this
$var='1 000';
float(str_ireplace(' ','', $var));
| |
doc_23526203
|
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setComponent(new ComponentName
("com.android.music","PlaylistBrowserActivity"));
intent.setType(MediaStore.Audio.Playlists.CONTENT_TYPE);
intent.setFlags(0x10000000);
intent.putExtra("oneshot", false);
intent.putExtra("playlist", playlistid);
startActivityForResult(intent,1);
I hit this exception -
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.example.playlistsonthego/com.example.playlistsonthego.HomeSceen}:
android.content.ActivityNotFoundException: Unable to find explicit
activity class {com.android.music/PlaylistBrowserActivity}; have you
declared this activity in your AndroidManifest.xml?
Can someone point me in the right direction? Thanks!
A: Try following
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType(MediaStore.Audio.Playlists.CONTENT_TYPE);
intent.putExtra("playlist", playlistid);
intent.putExtra("oneshot", false);
startActivityForResult(intent, 1);
what I have changed is from ACTION_VIEW to ACTION_PICK.
| |
doc_23526204
|
class DbConnection {
public static void main(String args[]) throws Exception
{
//Registering the driver
DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
//establish the connection with database
Connection con= DriverManager.getConnection("jdbc:oracle:thin:@194.16.247.96:1521:onlspn","onlinedbs", "onlinedbs");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select serno,amt_card from AUTHORIZATIONS where "
+ " SERNO > ( select max(SERNO)-200 from AUTHORIZATIONS ) and source "
+ "in ('VISA','MA01','MA02','MA03','MA10','MA11','MA12','AMA1','AMA2','AMP1','AMP2') order by serno desc");
while (rs.next()) {
int empid = rs.getInt("serno");
String fname = rs.getString("amt_card");
System.out.println(empid +'\t'+ fname);
}
}
}
Guys help me connect to my remote Database
A: I've tried out your code with ojdbc6.jar on the classpath, it compiles and runs fine.
However, when you run your code, it can't find a suitable driver. That can mean two things:
*
*(invalid option as pointed out by Andreas - the new OracleDriver() would fail) The driver isn't on the runtime classpath. Double check that it's included in the classpath when you run your program.
*(invalid option since the code runs fine in my test) There's a syntax error in your JDBC URL.
*You're using an old version of the Oracle JDBC driver. Download the latest ojdbc6.jar from http://www.oracle.com/technetwork/database/enterprise-edition/jdbc-112010-090769.html
| |
doc_23526205
| ||
doc_23526206
|
A: I think the question is whether the second line is "masked" by the first line.
Let say you camera point is C, and your segments are A1,A2 and B1,B2.
I would compute the cross products CA1xCB1 and CA2xCB2. The sign gives you if the point if the B1 point is on the left or the right of the CA1 line. It depends on how your triangles CA1A2 and CB1B2 are oriented (they must be oriented the same, they are many ways to do that).
You can then use the sign to know if you are in the following cases:
*
*CA1xCB1 is negative or CA2xCB2 is positive, then partially visible
*the opposite, then hidden.
You can also compute CA1xCB2 and CA2xCB1 to have fined grained cases.
A: slurdge's answer is a good start, but it's a bit more complicated than that.
If line segment 2 is closer to C than line segment 1, it could still be visible, e.g.
A1-------A2
B1-B2
C
Here B1 and B2 are "within" the A1A2 sector, but are not hidden.
The hardest one to work out is if B1 is 'between' A1 and A2, but closer to the camera, while B2 is 'not between' A1 and A2, but further from the camera:
B2
A1-----A2
B1
C
B1B2 could clip the edge of the line segment, thus rendering a small portion of B1B2 hidden (or maybe not!). I think you would have to find the intersection of A1A2 and B1B2 to check whether this actually happens.
| |
doc_23526207
|
I need to add dinamically the series because I do not know how many there will be
<template>
<div>
<!-- Begin Page Content -->
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<h2>Vue Js Google Pie Chart Demo</h2>
<GChart
type="ComboChart"
:options="options"
:data="data"
/>
</div>
</div>
</div>
</div>
</template>
<script>
import { GChart } from 'vue-google-charts/legacy'
export default {
name: "App",
components: {
GChart
},
created() {
this.getSaleReport();
},
methods: {
getSaleReport() {
this.loading = true; //the loading begin
axios.get('/api/sale/chart?api_token='+App.apiToken)
.then(response => {
console.log(response.data);
this.series = response.data;
this.qty = this.series.lenght-1;
})
.catch(function (error) {
console.log(error);
})
.finally(() => {
this.loading = false;
});
}
},
data() {
return {
posts: [],
qty: 0,
data: [
['Meds', 'Bolivia', 'Ecuador', 'Madagascar', 'Papua New Guinea', 'Rwanda', 'Average'],
['2004/05', 165, 938, 522, 998, 450, 100],
['2005/06', 135, 1120, 599, 1268, 288, -6],
['2006/07', 157, 1167, 587, 807, 397, -10],
['2007/08', 139, 1110, 615, 968, 215, 5],
['2008/09', 136, 691, 629, 1026, 366, 9]
],
options: {
title: 'Monthly Coffee Production by Country',
vAxes: [{
minValue: 1200,
maxValue: 2500
}, {
minValue: 0,
maxValue: 100
}],
hAxis: { title: 'Month' },
seriesType: 'bars',
series: {
0: {
type: "line",
targetAxisIndex: 1,
},
1: {
type: "line",
targetAxisIndex: 1,
},
2: {
type: "line",
targetAxisIndex: 1,
},
3: {
type: "line",
targetAxisIndex: 1,
},
4: {
type: "line",
targetAxisIndex: 1,
},
5: {
type: "line",
targetAxisIndex: 1,
}
},
width: '100%',
height: 600,
}
}
}
}
How can I add dinamically the series? I tried with axios but I add the this.series that it contains response.data and it did not work so I wonder how can I do it?
Thanks!
| |
doc_23526208
|
When I clean node_modules and do a reinstall (npm i) it does not reinstall the @typings. Should it do this?
James
A:
Should it do this?
Yes. To be clear the folder is called @types not @typings, perhaps that is confusing you. If not please installed latest node v6 (it comes with npm v3) since I just tested that.
| |
doc_23526209
|
When given a wrong socket (in purpose) the connection fails with the message:
INFO CassandraHostRetryService - Downed Host Retry service started with queue size -1 and retry delay 10s
ERROR HConnectionManager - Could not start connection pool for host 132.202.35.14(160.202.35.14):9160
INFO CassandraHostRetryService - Host detected as down was added to retry queue: 132.202.35.14(160.202.35.14):9160
INFO JmxMonitor - Registering JMX me.prettyprint.cassandra.service_RTBCluster:ServiceType=hector,MonitorType=hector
And it keeps on trying with java.net.ConnectException: Connection timed out: connect every few seconds.
I would like to know if the connection had failed or succeeded since once it succeeds I would like to take some actions.
My code looks like this:
CassandraHostConfigurator cassandraHostConfigurator = new CassandraHostConfigurator(this.socket);
cluster = new ThriftCluster(this.clusterName, cassandraHostConfigurator);
ConfigurableConsistencyLevel consistencyLevelPolicy = new ConfigurableConsistencyLevel();
consistencyLevelPolicy.setDefaultReadConsistencyLevel(getConsistencyLevelPolicy());
keyspace = HFactory.createKeyspace(keyspaceName, cluster, consistencyLevelPolicy);
fireConnectionEvent(true);
As you can see I'm firing a connection event, but I'm getting there anyways - whether connection succeeded or fails and I have no way to distinguish between the two.
Is there some event I can catch or any other way I can be informed of the connection state?
A: I'm not sure it's the optimal way, but since I could not find a better answer this is what I did:
Created this method:
private boolean isConnected() {
List<KeyspaceDefinition> keyspaces = null;
try {
keyspaces = cluster.describeKeyspaces();
} catch (HectorException e) {
return false;
}
return (!CollectionUtils.isEmpty(keyspaces));
}
and then:
if (isConnected())
fireConnectionEvent(true);
else {
LOG.error("Could not connect to socket " + this.socket + ". Connection to Cassandra is down!!!");
}
| |
doc_23526210
|
Both tables have records that mean the same thing, but written in a different, but similar way.
For instances TableA has:
|TableA.myFieldId |
|-----------------|
|MM0001P |
|HR0003P |
|MH0567P |
So as you can see all of the records are formated this way (with a P at the end):
([A-Z][A-Z][0-9][0-9][0-9][0-9]P)
then, TableB has:
|TableB.myFieldName |
|--------------------------------------------|
|MH-0567 Materials Handling important Role |
|MM-0001 Materials Management Minor Role |
|HR-0003 Human Resources Super Important Role|
So this one has the format (without 'P' at the end):
([A-Z][A-Z]-[0-9][0-9][0-9][0-9] ([A-Z]|[a-z]*))
First, I would like to make join queries with tableA and tableB on these fields, but as you can see, results will be NULL every time since both fields have completely different records.
So I would like to change every name in TableA.myFieldId with his corresponding name in TableB.myFieldName
Problem is, that both tables have around 1 million records, and the fields are repeated multiple times in both tables, plus I don't know how to do this (MS Access doesn't even let me use Regular Expressions).
A: I would make a table (or query, if it changes often enough) of all unique entries in the 2nd table and the corresponding key for the 1st table. Then use that table or query to help join the two tables.
Something like
Select myFieldName as FName, left(myFieldName,2) & mid(myFieldName,4,4) & "P" as FID
from TableB
group by FName, FID
Important note - are all IDs found in both files, or do you have records in either table that are not in the other? If they don't always match, you may need additional logic or steps to make a master table from both tableA and tableB.
| |
doc_23526211
|
Briefly what I'm trying to do:
*
*Hide select
*Create a parent div with text of first option and append it instead of original hidden select.
*Add eventListener on click to toggle class (it shows and hides children elements)
*Create inner divs with values and text of options from original hidden select.
*Add eventListener for each of them to replace a value of select.
These few lines of js and few lines of css gives my easy to style select.
// Define select and options
var select = document.getElementById('select');
var children = select.children;
// Recreate select via divs and keep same class
select.style.display = 'none';
var selectNew = document.createElement('div');
selectNew.className = select.classList;
selectNew.textContent = select.children[0].text;
select.parentNode.insertBefore(selectNew, select);
selectNew.addEventListener('click', function() {
toggleChildren();
});
function toggleChildren() {
selectNew.classList.toggle('active');
}
// remap children
var childArray = [];
for (var i = 0; i < children.length; i++) {
var child = document.createElement('div');
child.innerHTML = select.children[i].text;
child.dataset.value = select.children[i].value;
selectNew.appendChild(child);
childArray.push(child);
child.addEventListener("click", function () {
selectChoice();
});
}
function selectChoice() {
var which = childArray.indexOf( event.target || event.srcElement);
select.value = children[which].value;
// selectNew.textContent = children[which].text;
}
.select {
position: relative;
width: 100%;
line-height: 3em;
background: #eee;
}
.select > div {
position: absolute;
display: none;
width: 100%;
}
.select > div:nth-child(1) {
top: 2em;
}
.select > div:nth-child(2) {
top: 4em;
}
.select > div:nth-child(3) {
top: 6em;
}
.select > div:nth-child(4) {
top: 8em;
}
.select > div:nth-child(5) {
top: 10em;
}
.select > div:hover {
background: #eee;
}
.select.active > div {
display: block;
}
<select name="sortby" id="select" class="select">
<option value="val1">Value 1</option>
<option value="val2">Value 2</option>
<option value="val3">Value 3</option>
<option value="val4">Value 4</option>
<option value="val5">Value 5</option>
</select>
Whenever I try to update a text inside my parent element to show text of selected option via:
selectNew.textContent = children[which].text;
It kills previously added event Listener for this element. Can someone help me to understand what do I do wrong? That am I missing in behaviour of eventListeners?
A: The line you refer to does cause the problem, but not because it kills listener. It actually replaces the entire content of your selectNew with text.
What you want is replace the text of the first child, which is the textContent node.
If you change the line to:
selectNew.firstChild.textContent = children[which].text;
then everything works as expected.
JSFiddle here.
Bonus to answer
As to the additional question to add a listener to change event:
You cannot only use a listener for 'change' event on a div, only on form elements like input.
However, you can detect the change inside your click handler, like so:
function selectChoice() {
var which = childArray.indexOf(event.target || event.srcElement);
select.value = children[which].value;
if (selectNew.firstChild.textContent != children[which].text) {
alert('select value has been changed');
selectNew.firstChild.textContent = children[which].text;
}
}
Updated fiddle here
A: It doesn't kill your event, you are removing your option elements by setting the textContent so there is nothing to display when you click on the div. You need to set the textContent of the first TextNode of your div.
// Define select and options
var select = document.getElementById('select');
var children = select.children;
// Recreate select via divs and keep same class
select.style.display = 'none';
var selectNew = document.createElement('div');
selectNew.className = select.classList;
selectNew.textContent = select.children[0].text;
select.parentNode.insertBefore(selectNew, select);
selectNew.addEventListener('click', function(e) {
toggleChildren(e);
});
function toggleChildren() {
selectNew.classList.toggle('active');
}
// remap children
var childArray = [];
for (var i = 0; i < children.length; i++) {
var child = document.createElement('div');
child.innerHTML = select.children[i].text;
child.dataset.value = select.children[i].value;
selectNew.appendChild(child);
childArray.push(child);
child.addEventListener("click", function () {
selectChoice();
});
}
function selectChoice() {
var which = childArray.indexOf( event.target || event.srcElement);
select.value = children[which].value;
//get the first textnode and set its textContent
selectNew.childNodes[0].textContent = children[which].text;
}
.select {
position: relative;
width: 100%;
line-height: 3em;
background: #eee;
}
.select > div {
position: absolute;
display: none;
width: 100%;
}
.select > div:nth-child(1) {
top: 2em;
}
.select > div:nth-child(2) {
top: 4em;
}
.select > div:nth-child(3) {
top: 6em;
}
.select > div:nth-child(4) {
top: 8em;
}
.select > div:nth-child(5) {
top: 10em;
}
.select > div:hover {
background: #eee;
}
.select.active > div {
display: block;
}
<select name="sortby" id="select" class="select">
<option value="val1">Value 1</option>
<option value="val2">Value 2</option>
<option value="val3">Value 3</option>
<option value="val4">Value 4</option>
<option value="val5">Value 5</option>
</select>
| |
doc_23526212
|
#import <objc/Object.h>
#import <objc/objc-api.h>
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
@interface Object (Test)
-(id) doSomething:(id) anObject;
@end
typedef void *(*vafunc)(void *a1, void *a2, ...);
vafunc getvtest(void *s1);
int main(int argc, char *argv[])
{
id o1;
vafunc ptr;
int na;
ptr = getvtest(NULL);
na = 4;
(*ptr)(ptr, &na, "dog", "cat");
__objc_msg_forward = getvtest;
o1 = [[Object alloc] init];
[o1 doSomething:o1];
exit(0);
}
void *aptest(void *a1, void *a2, va_list ap)
{
fprintf(stderr, "Barfo\n");
return nil;
}
void *vtest(void *a1, void *a2, ...)
{
va_list ap;
void *ret = NULL;
fprintf(stderr, "Crasho\n");
va_start(ap, a2);
ret = aptest(a1, a2, ap);
va_end(ap);
return ret;
}
vafunc getvtest(void *s1)
{
return (vafunc) vtest;
}
What the heck am I doing wrong? When I run it this happens:
./vtest
Crasho
Barfo
Segmentation fault
If I pull it up in gdb it says Illegal Instruction.
A: Whose 64-bit Obj-C runtime are you using? As far as I know, Apple's only supporting the Obj-C 2.0 runtime on x86_64.
| |
doc_23526213
|
http://jsfiddle.net/boblauer/eCugY/
Basically, I want my userUpdated function to run when I update the user property, but it only runs once when the page loads.
Any help is appreciated.
A: Your problem is that you expect the userUpdated computed to fire when the user is updated because you set the user as the computed's context.
How these the KO computed work is, it first fires immediately and in the course of firing any observables that are encountered are recorded. When one of those observables is updated the computed function fires again. In your case your function calls no observables. It simply calls alert. The context object is not counted among the observables list.
You could get this to work by just using the user observable in your function. Alternativly you probably should be using a subscribe which is a function that get's called when an observable changes. Replace your computed with
user.name.subscribe(function(newvalue) {
alert('user updated to ' + newvalue);
});
Computed's are usually used to return computed values. If you start to use them as arbitrary function callers you can end up getting into infinite loops (if you decide to update an observable within the computed).
Hope this helps.
| |
doc_23526214
|
A[i,j] = (sum from k=1 to N) v[k]*B[k,i]*B[k,j]
A = np.einsum('k,ki,kj->ij',v,B,B)
I expect that this summation over the index k will result in an i x j matrix but am unsure if this is performing the summation or just the multiplication
| |
doc_23526215
|
deploy_to_AWS.yml
Within that yml I am using: (to configure the account I am pointing at)
- name: Configure AWS credentials
id: config-aws-creds
uses: aws-actions/configure-aws-credentials@v1
with:
aws-access-key-id: ${{ secrets.THIS_AWS_ACCESS_KEY_ID }}
aws-secret-access-key: ${{ secrets.THIS_AWS_SECRET_ACCESS_KEY }}
aws-region: eu-west-2
After that I have many different awscli commands e.g.:
- name: Run cron ecs
run: |
subnets=`aws ssm get-parameter --name "xxx_ecs_subnet" | jq -r '.Parameter.Value'`
security_group=`aws ssm get-parameter --name "xxx_ecs_security_group_id" | jq -r '.Parameter.Value'`
aws ecs run-task --cluster xxx-cluster --task-definition xxx-cron --count 1 --launch-type FARGATE --network-configuration "awsvpcConfiguration={subnets=[$subnets],securityGroups=[$security_group]}"
I want to use this tool: (https://github.com/nektos/act) to run the Github actions locally but I do not want real AWS calls to be made. I have had experience with a python library called moto in the past but I do not think this will work with the CLI.
A: Are you able to optionally pass in the "--dry-run" flag using a parameter or setting that only gets added when you are running locally?
| |
doc_23526216
|
list <- split(datainK, list(datainK$name), drop = TRUE)
filenames <- paste("~/DIR", names(list), ".dat")
filenames <- sapply(filenames,gsub,pattern=" .dat",replacement=".dat")
mapply(write.table, list, file = filenames,col.names = FALSE, row.names = FALSE, sep = "\t", quote = FALSE)
Many thanks!
A: I guess your filenames is not well defined.
Replace
filenames <- paste("~/DIR", names(list), ".dat")
by
filenames <- paste0("~/DIR/",names(list), ".dat")
| |
doc_23526217
|
In my case I'm querying an arbitrary website that returns a HUGE JSON string and I only care about a few of the (deeply nested) fields, so I don't want to take all that time to define a 'struct' to get at them.
Is it even possible to do this with "Decoder"? And if so, how does one go about it?
A: The question seems to be based on a misapprehension about how Decodable works. As a convenience, Decodable is willing to do some automatic code generation behind the scenes so that you can define a struct or nest of structs and just decode the entirety of the JSON. But you are not required to take advantage of that in order to decode JSON.
*
*There is no need to define struct properties for "fields" you don't care about. If a JSON dictionary contains 100 keys and your corresponding struct contains just one property, no problem; that key will be fetched, and no others.
*With regard to the "deeply nested" part, it should not take you much time to write simple nested structs that perform the dive to reach the dictionary you really care about. But if you don't want to do even that, you could write an implementation of init(from:) that dives down and fetches out the desired values.
In other words, if you think of Decodable as consisting primarily of your implementation of init(from:), and learn to write the code that it needs, you will see that this JSON can be parsed in a few quick simple lines of code.
As an example, here's a JSON sketch of a deeply nested piece of information with a bunch of extra information at every level that we want to ignore:
{
"ignore": true,
"outer1": {
"ignore": true,
"outer2": {
"ignore": true,
"outer3": {
"name": "matt",
"ignore": true
}
}
}
}
What I'd like to do is define a very simple struct Person that consists solely of the deeply nested name:
struct Person : Decodable {
let name : String
}
I can do that! To do so, I implement Decodable myself, supplying a "hoover" CodingKey adopter struct and an implementation of init(from:), like this (this may look like a lot of work, but it isn't, because the AnyCodingKey implementation is boilerplate, copied and pasted from here, and the init(coder:) implementation is just a few lines of code that were easy to write):
struct Person : Decodable {
let name : String
struct AnyCodingKey : CodingKey {
var stringValue: String
var intValue: Int?
init(_ codingKey: CodingKey) {
self.stringValue = codingKey.stringValue
self.intValue = codingKey.intValue
}
init(stringValue: String) {
self.stringValue = stringValue
self.intValue = nil
}
init(intValue: Int) {
self.stringValue = String(intValue)
self.intValue = intValue
}
}
init(from decoder: Decoder) throws {
var con = try! decoder.container(keyedBy: AnyCodingKey.self)
con = try! con.nestedContainer(keyedBy: AnyCodingKey.self, forKey: AnyCodingKey(stringValue:"outer1"))
con = try! con.nestedContainer(keyedBy: AnyCodingKey.self, forKey: AnyCodingKey(stringValue:"outer2"))
con = try! con.nestedContainer(keyedBy: AnyCodingKey.self, forKey: AnyCodingKey(stringValue:"outer3"))
let name = try! con.decode(String.self, forKey: AnyCodingKey(stringValue:"name"))
self.name = name
}
}
When I want to dive into the JSON and grab the name information, it's trivial:
let person = try! JSONDecoder().decode(Person.self, from: json)
The result is a Person object with name value "matt". Note that I didn't have to add any of the ignore keys and I didn't need to make a nest of structs.
A: Sure you can achieve this but with both JSonSerialization & Decodable , you have to serialize the json until reach the desired content then decode it ,but instead I recommend to create structs for root keys only then decode , think of it as it's a path from top to bottom don't decode a key that isn't in the path of your desired content
| |
doc_23526218
|
What is the purpose of the supervisor module that seems to be part of so many cowboy examples?
From the echo_get example:
%% Feel free to use, reuse and abuse the code in this file.
%% @private-module(echo_get_sup).
-behaviour(supervisor).
%% API.
-export([start_link/0]).
%% supervisor.
-export([init/1]).
%% API.
-spec start_link() -> {ok, pid()}.
start_link() ->
supervisor:start_link({local, ?MODULE}, ?MODULE, []).
%% supervisor.
init([]) ->
Procs = [],
{ok, {{one_for_one, 10, 10}, Procs}}.
A: From erlang application behavior documentation:
start is called when starting the application and should create the supervision tree by starting the top supervisor. It is expected to return the pid of the top supervisor and an optional term State, which defaults to []. This term is passed as-is to stop.
He has this dummy supervisor, so he can call it at the end of the start function here. I think it has no practical purpose except to satisfy this condition.
A: You don't need to specify all the children that a supervisor manages when it starts. You can add/start them dynamically using supervisor:start_child/2 and manage them using supevisor:restart_child/2, supervisor:terminate_child/2 and supervisor:delete_child/2. This means that even if a supervisor has no children from the beginning it does not mean it is just a dummy.
The comment that a real supervisor "doesn't do anything" most likely relates to the fact that a supervisor that can only supervisor processes and not do any work like worker processes. Or at least that's it should mean!
| |
doc_23526219
|
I am trying to get the Windows on-screen keyboard using PyWin32, but it doesn't execute properly.
Are there better ways to get this keyboard functionality into my application?
Please help me out.
A: import os
os.system("osk")
This will invoke the on screen keyboard, active for the window that invokes it.
| |
doc_23526220
|
This is my code so far:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:background="@color/background_color"
tools:context=".WelcomeActivity"
android:weightSum="1">
<TextView
android:layout_width="match_parent"
android:layout_height="55dp"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="a string of text"
android:textSize="30dp"
android:background="#cac09F"
android:id="@+id/textView2"
android:gravity="center_vertical|center_horizontal" />
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center_vertical|center_horizontal">
<Button android:id="@+id/btn1"
android:layout_width="80dp"
android:layout_height="80dp"
android:focusable="true"
android:background="@mipmap/icon_1">
</Button>
<Button android:id="@+id/btn2"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_marginLeft="50dp"
android:focusable="true"
android:layout_toRightOf="@+id/btn1"
android:background="@mipmap/icon_2">
</Button>
<TextView
android:id="@+id/txt1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="15sp"
android:text="Button 1"
android:layout_centerInParent="true"
android:layout_below="@id/btn1"/>
<TextView
android:id="@+id/txt2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="15sp"
android:text="Button 2"
android:layout_below="@+id/btn2"/>
</RelativeLayout>
</LinearLayout>
When i add android:layout_centerInParent="true" for both of the TextViews their right edge will be aligned with the right edge of btn2.
Heres a picture when btn1 has layout_centerInParent="true" and not btn2
A: Try with this:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@color/background_color"
android:orientation="vertical"
android:weightSum="1"
tools:context=".WelcomeActivity">
<TextView
android:id="@+id/textView2"
android:layout_width="match_parent"
android:layout_height="55dp"
android:background="#cac09F"
android:gravity="center_vertical|center_horizontal"
android:text="a string of text"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="30dp" />
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true">
<LinearLayout
android:id="@+id/ll1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<Button
android:id="@+id/btn1"
android:layout_width="80dp"
android:layout_height="80dp"
android:background="@mipmap/icon_1"
android:focusable="true" />
<TextView
android:layout_gravity="center_horizontal"
android:id="@+id/txt1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/btn1"
android:layout_centerInParent="true"
android:text="Button 1"
android:textSize="15sp" />
</LinearLayout>
<LinearLayout
android:layout_marginLeft="50dp"
android:layout_toRightOf="@+id/ll1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<Button
android:id="@+id/btn2"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_toRightOf="@+id/btn1"
android:background="@mipmap/icon_2"
android:focusable="true" />
<TextView
android:layout_gravity="center_horizontal"
android:id="@+id/txt2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/btn2"
android:text="Button 2"
android:textSize="15sp" />
</LinearLayout>
</RelativeLayout>
I used a relative layout as a parent and put the 2 buttons with their below text in 2 different linear layouts.
| |
doc_23526221
|
https://UserName:PassWord@Https://Secure.Website.com
Before the url comes up the warning dialog pops up first, since I know that the url I programmed is secure, I don't need the fishing site warning to pop up.
If anyone has any Ideas, I would greatly appreciate it. Thank you in advance.
A: You just cant do this.
This behavior is in private UIKit apis that you can't alter without being rejected from AppStore.
And for once, there is a good reason to this, a security reason :)
EDIT (after comments below)
I think you can disable these warnings in device settings : Settings App > Safari > Fraud Warning
Note that you can't do this with code from your app. You can only ask user to do so, or maybe by using Enterprise deployment facilities.
EDIT 2 About security concerns
*
*Again, there are very GOOD reason to this security, especially for a company concerned by its confidentiality/security.
*It is not because you set a static URL in a UIWebView that this is the URL you will get, phishing is not only from websites servers, it can also come from a middle man attack on the TCP/IP connection, DNS spoofing, or who knows, an admin going nuts :)
*Modifying private APIs is not easy, there is no source code, just assembly code that you can disassemble/analyze to figure a way to override/inject code doing what you want. It takes time that sorry I have not.
*In other words : you should find an alternative solution, like another URL without https (ask webmaster) but another security, not requesting data from UIWebView... I'm afraid there is no easy workaround. And I guess you know that URL authentication like you are trying to do is highly unsecure, any intermediate could just get the query and login/password.
*It is phishing and not fishing :)
*Do you know you can edit your comments on stackoverflow?
| |
doc_23526222
|
package mailsender;
import java.io.*;
import java.util.Scanner;
public class MailSenderList {
static String address=null;
static String name=null;
static String[][] mailer;
// @SuppressWarnings("empty-statement")
public static void main(String[] args) throws IOException {
try {
Scanner s = new Scanner(new BufferedReader(new FileReader("/home/fotis/Documents/MailRecipients.txt"),'\t')); //This is the path and the name of my file
for(int i=0;i>=30;i++){
for(int j=0;j>=2;j++){
if (s.hasNext());{
mailer[i][j]=s.next(); //here i am trying to put 1st+2 word into first column and 2nd+2 into second column.
}
}
}
for(int ii=0;ii>=30;ii++){
System.out.println("Line : ");
for(int ji=0;ji>=2;ji++){
System.out.print(" " + mailer[ii][ji]);
//trying to print and check the array
}
}
}
catch (java.io.FileNotFoundException e) {
System.out.println("Error opening file, ending program");
//System.exit(1);}
}
}
class mail{
mail(){
}
}
}
The file builds successfully but no result in System.out.In debugger, it seems as it never passes from the first for loop.
A: You probably made a mistake between < and >. Try switching i >= 30 in both for loops to i <= 30. Same with the j loops.
A: Indeed.For was so wrong.But I was dizzy.
Nevertheless , confusing "<>" was not the real problem.
The code worked with while.
Here is the whole class.
import java.io.File;
import java.util.Scanner;
public class ReadFile {
public static void main(String[] args) {
try {
File file = new File("/home/fotis/Documents/Mailers.txt"); //this a the path there
try (Scanner input = new Scanner(file).useDelimiter("\\t")) {
String line[] = new String[150000];
int i=0;
while (input.hasNextLine()) {
line[i] = input.next();
System.out.println(line[i]);
i++;
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
| |
doc_23526223
|
Dim clientID As String = "ClientID.apps.googleusercontent.com"
Dim body As New Moment
Dim target As New ItemScope
target.Id = "1"
target.Image = "Image"
target.Type = "http://schemas.google.com/AddActivity"
target.Description = _PostContent
target.Url = _LinkedBackURL
target.Name = _PostName
body.Target = target
body.Type = "http://schemas.google.com/AddActivity"
Dim insert As New MomentsResource.InsertRequest(PlusService(), body, clientID, MomentsResource.Collection.Vault)
Dim wrote As Moment = insert.Fetch()
End Function
Private Function BuildAuth() As BaseClientService.Initializer
Dim Service_Account_Email As String = "yourserviceaccount@developer.gserviceaccount.com"
Dim Service_Account_PKCS12_File_Path As String = "Certificate Path"
Dim certificate As X509Certificate2 = New X509Certificate2(Service_Account_PKCS12_File_Path, "notasecret", X509KeyStorageFlags.Exportable)
Dim GoogleAuthServer As DotNetOpenAuth.OAuth2.AuthorizationServerDescription = GoogleAuthenticationServer.Description
GoogleAuthServer.AuthorizationEndpoint = New Uri(GoogleAuthServer.AuthorizationEndpoint.AbsoluteUri + "?" + "data-requestvisibleactions=AddActivity" + "&" + "access_type=offline")
Dim provider As New Authentication.OAuth2.DotNetOpenAuth.AssertionFlowClient(GoogleAuthServer, certificate) With {.ServiceAccountId = Service_Account_Email, .Scope = Plus.v1.PlusService.Scopes.PlusLogin.GetStringValue()}
Dim auth As New OAuth2Authenticator(Of Authentication.OAuth2.DotNetOpenAuth.AssertionFlowClient)(provider, AddressOf Authentication.OAuth2.DotNetOpenAuth.AssertionFlowClient.GetState)
Dim init As New Google.Apis.Services.BaseClientService.Initializer
init.ApiKey = "API Key"
init.Authenticator = auth
Return init
End Function
Private Function PlusService() As PlusService
Dim ps As New PlusService(BuildAuth)
Return ps
End Function
| |
doc_23526224
|
context.beginPath();
context.moveTo(30, 20);
context.lineTo(some_value1,some_value2);
context.lineTo(some_value3,some_value4);
context.closePath();
But this method is suitable for drawing, on two sides.
I hope now I have described the problem in detail. Thanks in advance.
A: You will need to compute cartesian coordinates of each point first. You can set the first point to [0, 0], and the second will be at [x1, 0] where x1 is length of first line. Third point needs to be calculated, take a look here how this can be done:
https://math.stackexchange.com/questions/543961/determine-third-point-of-triangle-when-two-points-and-all-sides-are-known
// hardcoded, but you would get those from user
var AB = 40;
var BC = 50;
var AC = 30;
var A = [0, 0]; // starting coordinates
var B = [0, AB];
var C = [];
// calculate third point
C[1] = (AB * AB + AC * AC - BC * BC) / (2 * AB);
C[0] = Math.sqrt(AC * AC - C[1] * C[1]);
console.log(A, B, C);
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.moveTo(A[0], A[1]);
ctx.lineTo(B[0], B[1]);
ctx.lineTo(C[0], C[1]);
ctx.fill();
<canvas id="canvas" width="500" height="500"></canvas>
| |
doc_23526225
|
My model was overfitting so I added dropout and FC layers with batch normalization to see how it goes. But still, the model overfits:
train_data_path = 'dataset_cfps/train'
validation_data_path = 'dataset_cfps/validation'
#Parametres
img_width, img_height = 224, 224
vggface = VGGFace(model='resnet50', include_top=False, input_shape=(img_width, img_height, 3))
last_layer = vggface.get_layer('avg_pool').output
x = Flatten(name='flatten')(last_layer)
xx = Dense(1024, activation = 'softmax')(x)
x2 = Dropout(0.5)(xx)
y = Dense(1024, activation = 'softmax')(x2)
yy = BatchNormalization()(y)
y1 = Dropout(0.5)(yy)
x3 = Dense(12, activation='softmax', name='classifier')(y1)
custom_vgg_model = Model(vggface.input, x3)
# Create the model
model = models.Sequential()
# Add the convolutional base model
model.add(custom_vgg_model)
model.summary()
model = load_model('facenet_resnet_lr3_SGD_relu_1024.h5')
train_datagen = ImageDataGenerator(
rescale=1./255,
rotation_range=20,
width_shift_range=0.2,
height_shift_range=0.2,
horizontal_flip=True,
fill_mode='nearest')
validation_datagen = ImageDataGenerator(rescale=1./255)
# Change the batchsize according to your system RAM
train_batchsize = 32
val_batchsize = 32
train_generator = train_datagen.flow_from_directory(
train_data_path,
target_size=(img_width, img_height),
batch_size=train_batchsize,
class_mode='categorical')
validation_generator = validation_datagen.flow_from_directory(
validation_data_path,
target_size=(img_width, img_height),
batch_size=val_batchsize,
class_mode='categorical',
shuffle=True)
# Compile the model
model.compile(loss='categorical_crossentropy',
optimizer=optimizers.SGD(lr=1e-3),
metrics=['acc'])
# Train the model
history = model.fit_generator(
train_generator,
steps_per_epoch=train_generator.samples/train_generator.batch_size ,
epochs=100,
validation_data=validation_generator,
validation_steps=validation_generator.samples/validation_generator.batch_size,
verbose=1)
# Save the model
model.save('facenet_resnet_lr3_SGD_relu_1024_1.h5')
Here are the epochs:
(type) Output Shape Param #
=================================================================
model_5 (Model) (None, 12) 26725324
=================================================================
Total params: 26,725,324
Trainable params: 26,670,156
Non-trainable params: 55,168
_________________________________________________________________
Found 1774 images belonging to 12 classes.
Found 313 images belonging to 12 classes.
.
.
.
Epoch 70/100
56/55 [==============================] - 49s 880ms/step - loss: 0.5433 - acc: 0.8987 - val_loss: 0.8271 - val_acc: 0.7796
Epoch 71/100
56/55 [==============================] - 49s 880ms/step - loss: 0.5353 - acc: 0.9145 - val_loss: 0.7954 - val_acc: 0.7508
Epoch 72/100
56/55 [==============================] - 49s 880ms/step - loss: 0.5353 - acc: 0.8955 - val_loss: 0.8690 - val_acc: 0.7348
Epoch 73/100
56/55 [==============================] - 49s 880ms/step - loss: 0.5310 - acc: 0.9037 - val_loss: 0.8673 - val_acc: 0.7476
Epoch 74/100
56/55 [==============================] - 49s 880ms/step - loss: 0.5189 - acc: 0.8943 - val_loss: 0.8701 - val_acc: 0.7380
Epoch 75/100
56/55 [==============================] - 49s 880ms/step - loss: 0.5333 - acc: 0.8952 - val_loss: 0.9399 - val_acc: 0.7188
Epoch 76/100
56/55 [==============================] - 49s 879ms/step - loss: 0.5106 - acc: 0.9043 - val_loss: 0.8107 - val_acc: 0.7700
Epoch 77/100
56/55 [==============================] - 49s 880ms/step - loss: 0.5108 - acc: 0.9064 - val_loss: 0.9624 - val_acc: 0.6869
Epoch 78/100
56/55 [==============================] - 49s 880ms/step - loss: 0.5214 - acc: 0.8994 - val_loss: 0.9602 - val_acc: 0.6933
Epoch 79/100
56/55 [==============================] - 49s 880ms/step - loss: 0.5246 - acc: 0.9009 - val_loss: 0.8379 - val_acc: 0.7572
Epoch 80/100
56/55 [==============================] - 49s 879ms/step - loss: 0.4859 - acc: 0.9082 - val_loss: 0.7856 - val_acc: 0.7796
Epoch 81/100
56/55 [==============================] - 49s 881ms/step - loss: 0.5005 - acc: 0.9175 - val_loss: 0.7609 - val_acc: 0.7827
Epoch 82/100
56/55 [==============================] - 49s 880ms/step - loss: 0.4690 - acc: 0.9294 - val_loss: 0.7671 - val_acc: 0.7636
Epoch 83/100
56/55 [==============================] - 49s 879ms/step - loss: 0.4897 - acc: 0.9146 - val_loss: 0.7902 - val_acc: 0.7636
Epoch 84/100
56/55 [==============================] - 49s 879ms/step - loss: 0.4604 - acc: 0.9291 - val_loss: 0.7603 - val_acc: 0.7636
Epoch 85/100
56/55 [==============================] - 49s 881ms/step - loss: 0.4750 - acc: 0.9220 - val_loss: 0.7325 - val_acc: 0.7668
Epoch 86/100
56/55 [==============================] - 49s 879ms/step - loss: 0.4524 - acc: 0.9266 - val_loss: 0.7782 - val_acc: 0.7636
Epoch 87/100
56/55 [==============================] - 49s 880ms/step - loss: 0.4643 - acc: 0.9172 - val_loss: 0.9892 - val_acc: 0.6901
Epoch 88/100
56/55 [==============================] - 49s 881ms/step - loss: 0.4718 - acc: 0.9177 - val_loss: 0.8269 - val_acc: 0.7380
Epoch 89/100
56/55 [==============================] - 49s 879ms/step - loss: 0.4646 - acc: 0.9290 - val_loss: 0.7846 - val_acc: 0.7604
Epoch 90/100
56/55 [==============================] - 49s 879ms/step - loss: 0.4433 - acc: 0.9341 - val_loss: 0.7693 - val_acc: 0.7764
Epoch 91/100
56/55 [==============================] - 49s 877ms/step - loss: 0.4706 - acc: 0.9196 - val_loss: 0.8200 - val_acc: 0.7604
Epoch 92/100
56/55 [==============================] - 49s 880ms/step - loss: 0.4572 - acc: 0.9184 - val_loss: 0.9220 - val_acc: 0.7220
Epoch 93/100
56/55 [==============================] - 49s 880ms/step - loss: 0.4479 - acc: 0.9175 - val_loss: 0.8781 - val_acc: 0.7348
Epoch 94/100
56/55 [==============================] - 49s 879ms/step - loss: 0.4793 - acc: 0.9100 - val_loss: 0.8035 - val_acc: 0.7572
Epoch 95/100
56/55 [==============================] - 49s 879ms/step - loss: 0.4329 - acc: 0.9279 - val_loss: 0.7750 - val_acc: 0.7796
Epoch 96/100
56/55 [==============================] - 49s 879ms/step - loss: 0.4361 - acc: 0.9212 - val_loss: 0.8124 - val_acc: 0.7508
Epoch 97/100
56/55 [==============================] - 49s 880ms/step - loss: 0.4371 - acc: 0.9202 - val_loss: 0.9806 - val_acc: 0.7029
Epoch 98/100
56/55 [==============================] - 49s 880ms/step - loss: 0.4298 - acc: 0.9149 - val_loss: 0.8637 - val_acc: 0.7380
Epoch 99/100
56/55 [==============================] - 49s 880ms/step - loss: 0.4370 - acc: 0.9255 - val_loss: 0.8349 - val_acc: 0.7604
Epoch 100/100
56/55 [==============================] - 49s 880ms/step - loss: 0.4407 - acc: 0.9205 - val_loss: 0.8477 - val_acc: 0.7508
A: CNN deep networks need a huge data for training. You have a little dataset and the model is unable to generalize from this small dataset. You have two options
*
*reduce the network size
*increase the number of dataset
EDIT after comments on answer:
The model has some issues. You wouldn't use softmax for hidden layers.
If you want to overcome the over-fitting issue you would freeze the trained layers and train only new added layers. If the model still overfits, you may remove some of layers you have added or lower their number of units.
| |
doc_23526226
|
- name: Add existing S3 bucket and object to Stack
run: aws cloudformation create-change-set
--stack-name ${{ env.STACK_NAME }} --change-set-name ImportChangeSet
--change-set-type IMPORT
--resources-to-import file://ResourcesToImport.txt
--template-url https://cf-templates.s3.eu-central-1.amazonaws.com/ResourcesToImport.yaml
I'm a little confused to what exactly should the ResourcesToImport.txt and ResourcesToImport.yaml contain. I currently have:
ResourcesToImport.txt
[
{
"ResourceType":"AWS::S3::Bucket",
"LogicalResourceId":"myBucket",
"ResourceIdentifier": {
"resourceName":"myBucket",
"resourceType":"AWS::S3::Bucket"
}
}
]
NB: As a sidenote, I have just used the bucket name, but actually I just want a specific folder within that bucket.
ResourcesToImport.yaml
AWSTemplateFormatVersion: '2010-09-09'
Description: Import existing resources
Resources:
S3SourceBucket:
Type: AWS::S3::Bucket
DeletionPolicy: Retain
BucketName: myBucket
I'm quite sure the replication of information in both of these files is redundant and incorrect. The ResourcesToImport.yaml file is uploaded in advance to the bucket cf-templates/ResourcesToImport.yaml
What should these two files actually contain, if I am to import only an existing S3 bucket and folder?
EDIT
In addition to the template route, I also tried adding the S3 bucket via the console. However when the S3 url is added (s3://myBucket/folder1/folder2/), I get:
S3 error: Domain name specified in myBucket is not a valid S3 domain
A: Here's what the two file inputs to create-change-set should contain when importing:
--resources-to-import The resources to import into your stack. This identifies the to-be-imported resources. Not a template. Make sure the LogicalResourceId matches the resource id in the template below. In your case: "LogicalResourceId": "S3SourceBucket".
--template-url The [S3] location of the file that contains the revised template. This is a CloudFormation template that includes (a) the to-be-imported resources AND (b) the existing stack resources. This is what CloudFormation will deploy when you execute the change set. Note: alternatively, use --template-body with a local file template instead.
Regarding your EDIT:
Bucket names cannot contain slashes. Object Keys can. S3 does not have folders per se, although object keys with a / have some folder-like properties. The path/to/my.json together is the S3 object Key name:
Amazon S3 supports buckets and objects, and there is no hierarchy. However, by using prefixes and delimiters in an object key name, the Amazon S3 console and the AWS SDKs can infer hierarchy and introduce the concept of folders
| |
doc_23526227
|
Does f_count member of struct file indicates the number of open instances of the same file ? If so, does kernel create one file struct for every opened file instance ?
Example : /users/soverflow/test.txt
If processes P1, P1 and P3 opens the same file "/users/soverflow/test.txt", does kernel create "three" file struct corresponding to P1, P2 and P3 or does it create only one file struct and all the processes points to the same structure ?
If all the processes points to the same structure, how do they know current file position ?
A: The file structure tracks a single instance of an opened file. In the scenario you describe, each process will get its own copy of the structure. The f_count member of the structure is used to track multiple file descriptors referring to the same instance of the file. And f_pos is used to track the current file position for each instance.
f_count can be incremented by dup(2) as well as by fork(2). dup creates another unique file descriptor which refers to exactly the same open file instance. Likewise, when your process calls fork, the parent and child processes both have references to the same file instances. Multiple file descriptors that reference the same struct file share the file position it tracks.
Example:
If your process calls open(2) on the same file twice, it will get two file descriptors each referring to a separate instance of struct file (each with f_count set to 1). But if it calls open once, then calls dup with the returned file descriptor, it will still have two file descriptors but each now refers to the same single struct file with f_count set to 2.
| |
doc_23526228
|
I am looking for ways to assign a fixed Driveletter to USB Drives on Windows Server 2012 (Foundation).
The Scenario:
One of my smaller customers has 2 USB Drives for his serverbackup, which are swapped every day to have an offsite backup. Currently they are manually reassigning the Driveletters if there is a mismatch.
I already have a plan to realize this but wanted to ask for advice before implementing it since i am not sure this is the best possible solution.
I would go about it the following way:
*
*Enable the DriverFramework-UserMode log if it is not enabled
*Create a scheduled task triggered by EventID 2106
*run a powershell script (via the scheduled task) that assigns the driveletter if the DeviceID matches one of the backup drives
So the question is:
Is it somehow possible to assign a fixed driveletter to a set of usb devices without having to run a script everytime a device is attached?
And if not is there a better way to detect when a device is attached and trigger the task?
Of course i did some research but only found solutions for Windows7 or Server2008. I would prefer to solve this without 3rd party tools.
Thank you in advance for any insight you can give on this topic
Regards Paul
A: I don't know if this helps much, but I found a nice post at https://social.technet.microsoft.com/Forums/windowsserver/en-US/09c9814a-38fa-4b16-bc8f-01329882a791/powershell-wmi-get-usb-storage-devices-only where the following code helps detect a connected USB device:
$diskdrive = gwmi win32_diskdrive | ?{$_.interfacetype -eq "USB"}
$letters = $diskdrive | %{gwmi -Query "ASSOCIATORS OF {Win32_DiskDrive.DeviceID=`"$($_.DeviceID.replace('\','\\'))`"} WHERE AssocClass = Win32_DiskDriveToDiskPartition"} | %{gwmi -Query "ASSOCIATORS OF {Win32_DiskPartition.DeviceID=`"$($_.DeviceID)`"} WHERE AssocClass = Win32_LogicalDiskToPartition"} | %{$_. deviceid}
$drive = gwmi win32_volume | ? {$letters -contains ($_.name -replace "\\")}
Then you can change the drive letter with the following (must be admin)
$drive.DriveLetter = "O:"
$drive.Put()
EDIT
OK here is another try. The following code (which I found here: http://blogs.technet.com/b/heyscriptingguy/archive/2010/04/13/hey-scripting-guy-april-13-2010.aspx) allows to create a WMI event which will fire when a USB drive is plugged in.
I've added an action to that event so that a script block executes.
The script block checks the letter of the USB drive and if it's not, say, "O:", it will set it.
I didn't use Wait-Job, as the job will continue running for as long as the event exists, and I wanted to see some output for testing.
In anycase, this should be closer to what you want to do:
$scriptblock = {
$driveLetter = "O:"
$diskdrive = gwmi win32_diskdrive | ?{$_.interfacetype -eq "USB"}
$letters = $diskdrive | %{gwmi -Query "ASSOCIATORS OF {Win32_DiskDrive.DeviceID=`"$($_.DeviceID.replace('\','\\'))`"} WHERE AssocClass = Win32_DiskDriveToDiskPartition"} | %{gwmi -Query "ASSOCIATORS OF {Win32_DiskPartition.DeviceID=`"$($_.DeviceID)`"} WHERE AssocClass = Win32_LogicalDiskToPartition"} | %{$_. deviceid}
$drive = gwmi win32_volume | ? {$letters -contains ($_.name -replace "\\")}
if ($drive.DriveLetter -ne $driveLetter)
{
$drive.DriveLetter = $driveLetter
$drive.Put()
}
$drive.DriveLetter
}
$job = Register-WmiEvent -Query "Select * from __InstanceCreationEvent within 5 where targetinstance isa 'win32_logicaldisk'" -SourceIdentifier usb -Timeout 1000 -Action $scriptblock
while ($job.State -ne 'Stopped')
{
$job | Receive-Job
sleep 5
}
Unregister-Event -SourceIdentifier usb -Force | Out-Null
$job | Remove-Job -force
Worth noting:
The script block will receive $args as well as $event. I didn't use them but they will probably help optimize the script further.
A: Here is the code i will probably end up using:
To create a permanent wmi consumer that runs a script:
$computer = "xxx"
$filterNS = "root\cimv2"
$wmiNS = "root\subscription"
$query = "Select * from __InstanceCreationEvent within 5 where targetinstance isa 'win32_logicaldisk'"
$filterName = "TestFilter"
$filterPath = Set-WmiInstance -Class __EventFilter `
-ComputerName $computer -Namespace $wmiNS -Arguments `
@{name=$filterName; EventNameSpace=$filterNS; QueryLanguage="WQL";
Query=$query}
$consumerPath = Set-WmiInstance -Class CommandLineEventConsumer `
-ComputerName $computer -Namespace $wmiNS `
-Arguments @{
name="TestConsumer";
ExecutablePath= "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe";
CommandLineTemplate = "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe -executionpolicy bypass -file D:\\reassignDriveletter.ps1"
}
Set-WmiInstance -Class __FilterToConsumerBinding -ComputerName $computer `
-Namespace $wmiNS -arguments @{Filter=$filterPath; Consumer=$consumerPath} |
out-null
And here is the script that changes the driveletter if the Serialnumber of the drive matches one of the Backupdrives
$driveLetter = "Z:"
$diskdrive = gwmi win32_diskdrive | ?{($_.interfacetype -eq "USB") -and $_.serialnumber.trim() -eq "761203FA9J813S" -or $_.serialnumber.trim() -eq "761239FA9J813S"}
$letters = $diskdrive | %{gwmi -Query "ASSOCIATORS OF {Win32_DiskDrive.DeviceID=`"$($_.DeviceID.replace('\','\\'))`"} WHERE AssocClass = Win32_DiskDriveToDiskPartition"} | %{gwmi -Query "ASSOCIATORS OF {Win32_DiskPartition.DeviceID=`"$($_.DeviceID)`"} WHERE AssocClass = Win32_LogicalDiskToPartition"} | %{$_. deviceid}
$drive = gwmi win32_volume | ? {$letters -contains ($_.name -replace "\\")}
if ($drive.DriveLetter -ne $driveLetter)
{
$drive.DriveLetter = $driveLetter
$drive.Put()
}
| |
doc_23526229
|
For example:
This is a markdown file. Here is a [link](www.example.com).
Here is some inline math: $\sigma_{i=1}^n \frac{\mu}{100}$
Here is an equation:
$$ y = mx + b $$
How can I convert a markdown file with the above text into an ePub file?
I've experimented with different methods of conversion using Pandoc; however, I still can not find a solution which renders the math even 50% correct.
Can anyone provide any help as to how I can do this?
I've tried this solution as well as other Pandoc option without success. Thanks in advance for the help.
A: Pandoc has an EPUB3 writer. It renders latex math into MathML, which EPUB3 readers are supposed to support (but unfortunately still few do). Use pandoc -t epub3 to force EPUB3 output, as opposed to EPUB2 which is the default.
Of course, this isn't much help if you want EPUB2 output or target readers that don't support MathML. Then you could try using the --webtex option, which will use a web service to convert the TeX to an image.
| |
doc_23526230
|
self.childVC = ChildViewController()
self.childVC.delegate = self
func addChildViewController () {
self.addChildViewController(self.childVC)
self.childVC.view.frame = CGRect(x: x, y: y, width: widthOfContainerView, height: heightOfContainerView)
self.view.addSubview(self.childVC.view)
self.childVC.didMove(toParentViewController: self)
}
I'm having a keyboard presented when the user taps the UITextField, and I'd like the keyboard to be dismissed whenever the user taps outside the text field - which is either going to be within the child view controller's view, or the parent view controller's view.
Right now I'm redundantly setting up a tap gesture recognizer in both the child and parent view controllers to pull this off.
func setupTapGestureRecognizer() {
let tap = UITapGestureRecognizer(target: self, action: #selector(self.handleTap(_:)))
view.addGestureRecognizer(tap)
view.isUserInteractionEnabled = true
}
@objc func handleTap(_ sender: UITapGestureRecognizer) {
view.endEditing(true)
}
As a beginner, I suspect it's not great practice to have redundant code like this in my project, but I can't come up with any other ways to handle this.
What are some other ways I can ensure that tapping outside the textfield will dismiss the keyboard regardless of whether the user taps in the child view or parent view?
Thanks.
A: 5 years in and this is still one of the most annoying aspects of iOS that I have to deal with. Unfortunately I have not personally seen a drop-in approach that handles all the issues, but here's my approach FWIW:
First, instead of messing with view.endEditing or manually resigning first responder for the individual items, I tend to use the catch all:
UIApplication.shared.sendAction(Selector(resignFirstResponder), to: nil, from: nil, for: nil).
This easily takes care of general cases, as well as cases where the first responder (TextField in your example) may not be in the same View stack as the view being tapped. This also lends itself to being added as an extension in whatever way you prefer.
Aside from that it's really about maximizing coverage of your tapGestures. Here are some options I use:
*
*As @IraniyaNaynesh mentioned, fiddle with userInteractionEnabled to have taps fall through to the layer underneath where everything is handled.
*Make subclasses of UIView, UILabel, etc. that automatically handle taps to call resignFirstResponder.
*Dynamically add/remove a set of clear views while a TextField is editing. (Not ideal, but there are some circumstances were I've found this to be the simplest solution).
Hopefully someone out there (or Apple) can come up with a simpler solution for this!
A: When you load a child view controller and add its view as a subview of the "parent" view controller, that view becomes part of the parent's view hierarchy.
Instead of adding Tab recognizers, you could simply use touchesBegan().
In the "parent" VC, add this:
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
view.endEditing(true)
}
This will be triggered by a touch anywhere in the "child view" or in the "parent view". And, since the text field in the child view is also part of the view hierarchy, this will dismiss the keyboard.
This shows the relationship with an embedded VC (using Container View in Storyboard), but it will have the same behavior when loaded via code:
Touching anywhere in the blue "child view" or in the white "parent view" will trigger touchesBegan in the parent VC.
| |
doc_23526231
|
let (:new_post) {Post.make!}
before do
Post.stub!(:new).and_return(new_post)
end
This used to work, and now I get the following error:
1) PostsController GET index assigns all posts as @posts
Failure/Error: let (:new_post) {Post.make!}
NoMethodError:
undefined method `title=' for nil:NilClass
# ./spec/support/blueprints.rb:22:in `block in <top (required)>'
# ./spec/controllers/posts_controller_spec.rb:37:in `block (2 levels) in <top (required)>'
# ./spec/controllers/posts_controller_spec.rb:40:in `block (2 levels) in <top (required)>'
Here is my blueprint:
require 'machinist/active_record'
Post.blueprint do
title {"Post"}
body {"hello world"}
end
For now my work around is to create them using instance variables within the before do block, but it would be nice to use the 'let' calls as it keeps my rspec tests cleaner.
A: Funny, I just ran across the exact same problem, although I'm on Rails 3.2.1, Machinist 2.0, and ruby 1.9.2-p290. I think there's a conflict between the execution of the Post.stub(:new) stub method and the Machinist make method, but I haven't dug into the code.
The best solution I've come up with is:
before do
new_post
Post.stub!(:new).and_return(new_post)
end
This will initialize the let (since let is lazy-loaded in rspec) before it gets to the stub method. It's hacky, but at least you (and I) can keep the let statement.
| |
doc_23526232
|
The program that keeps a workbook open for hours at a time, and does manipulations like adding/editing text, shapes, and calling macros.
I have not once seen a Marshal.ReleaseComObject. Yet, the users don't report any problems.
In all cases, the objects go out of scope within several seconds.
So, is this a problem? How? If yes, how do I justify to management that it needs cleanup? If not, why recommend it in the first place?
A: It's been a while, but I did a lot of Excel automation from .NET. I never used Marshal.ReleaseComObject either. Never saw a problem.
| |
doc_23526233
|
public static function find($slug)
{
return static::all()->firstWhere("slug", $slug);
}
public static function all()
{
return collect(File::files(resource_path("posts")))
->map(fn($file) => YamlFrontMatter::parseFile($file))
->map(fn($document) => new Post(
$document->title,
$document->excerpt,
$document->date,
$document->slug,
$document->body(),
));
}
But when I do static::all()-> it gives me 0 code hinting.
I have Laravel Idea plugin.
I install laravel-ide-helper and generated it.
I install require doctrine/dbal
I cannot get the code hinting.
| |
doc_23526234
|
i installed the script and its dependencies with linux.
from here http://milianw.de/code-snippets/take-2-download-script-for-springerlinkcom-ebooks and here https://github.com/milianw/springer_download
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import getopt
import urllib
import re
import tempfile
import shutil
import subprocess
# Set some kind of User-Agent so we don't get blocked by SpringerLink
class SpringerURLopener(urllib.FancyURLopener):
version = "Mozilla 5.0"
def pdfcat(fileList, bookTitlePath):
if findInPath("pdftk") != False:
command = [findInPath("pdftk")]
command.extend(fileList)
command.extend(["cat", "output", bookTitlePath])
subprocess.Popen(command, shell=False).wait()
elif findInPath("stapler") != False:
command = [findInPath("stapler"), "cat"]
command.extend(fileList)
command.append(bookTitlePath)
subprocess.Popen(command, shell=False).wait()
else:
error("You have to install pdftk (http://www.accesspdf.com/pdftk/) or stapler (http://github.com/hellerbarde/stapler).")
# validate CLI arguments and start downloading
def main(argv):
if not findInPath("iconv"):
error("You have to install iconv.")
#Test if convert is installed
if os.system("convert --version > /dev/null 2>&1")!=0:
error("You have to install the packet ImageMagick in order to use convert")
try:
opts, args = getopt.getopt(argv, "hl:c:n", ["help", "link=", "content=", "no-merge"])
except getopt.GetoptError:
error("Could not parse command line arguments.")
link = ""
hash = ""
merge = True
for opt, arg in opts:
if opt in ("-h", "--help"):
usage()
sys.exit()
elif opt in ("-c", "--content"):
if link != "":
usage()
error("-c and -l arguments are mutually exclusive")
hash = arg
elif opt in ("-l", "--link"):
if hash != "":
usage()
error("-c and -l arguments are mutually exclusive")
match = re.match("(https?://)?(www\.)?springer(link)?.(com|de)/(content|.*book)/(?P<hash>[a-z0-9\-]+)/?(\?[^/]*)?$", arg)
if not match:
usage()
error("Bad link given. See example link.")
hash = match.group("hash")
elif opt in ("-n", "--no-merge"):
merge = False
if hash == "":
usage()
error("Either a link or a hash must be given.")
if merge and not findInPath("pdftk") and not findInPath("stapler"):
error("You have to install pdftk (http://www.accesspdf.com/pdftk/) or stapler (http://github.com/hellerbarde/stapler).")
baseLink = "http://www.springerlink.com/content/" + hash + "/"
link = baseLink + "contents/"
chapters = list()
loader = SpringerURLopener();
curDir = os.getcwd()
bookTitle = ""
coverLink = ""
front_matter = False
while True:
# download page source
try:
print "fetching book information...\n\t%s" % link
page = loader.open(link,"MUD=MP").read()
except IOError, e:
error("Bad link given (%s)" % e)
if re.search(r'403 Forbidden', page):
error("Could not access page: 403 Forbidden error.")
if bookTitle == "":
match = re.search(r'<h1[^<]+class="title">(.+?)(?:<br/>\s*<span class="subtitle">(.+?)</span>\s*)?</h1>', page, re.S)
if not match or match.group(1).strip() == "":
error("Could not evaluate book title - bad link %s" % link)
else:
bookTitle = match.group(1).strip()
# remove tags, e.g. <sub>
bookTitle = re.sub(r'<[^>]*?>', '', bookTitle)
# subtitle
if match and match.group(2) and match.group(2).strip() != "":
bookTitle += " - " + match.group(2).strip()
# edition
#match = re.search(r'<td class="labelName">Edition</td><td class="labelValue">([^<]+)</td>', page)
#if match:
#bookTitle += " " + match.group(1).strip()
## year
#match = re.search(r'<td class="labelName">Copyright</td><td class="labelValue">([^<]+)</td>', page)
#if match:
#bookTitle += " " + match.group(1).strip()
## publisher
#match = re.search(r'<td class="labelName">Publisher</td><td class="labelValue">([^<]+)</td>', page)
#if match:
#bookTitle += " - " + match.group(1).strip()
# coverimage
match = re.search(r'<div class="coverImage" title="Cover Image" style="background-image: url\(/content/([^/]+)/cover-medium\.gif\)">', page)
if match:
coverLink = "http://www.springerlink.com/content/" + match.group(1) + "/cover-large.gif"
bookTitlePath = curDir + "/%s.pdf" % sanitizeFilename(bookTitle)
if bookTitlePath == "":
error("could not transliterate book title %s" % bookTitle)
if os.path.isfile(bookTitlePath):
error("%s already downloaded" % bookTitlePath)
print "\nNow Trying to download book '%s'\n" % bookTitle
#error("foo")
# get chapters
for match in re.finditer('href="([^"]+\.pdf)"', page):
chapterLink = match.group(1)
if chapterLink[:7] == "http://": # skip external links
continue
if re.search(r'front-matter.pdf', chapterLink):
if front_matter:
continue
else:
front_matter = True
if re.search(r'back-matter.pdf', chapterLink) and re.search(r'<a href="([^"#]+)"[^>]*>Next</a>', page):
continue
#skip backmatter if it is in list as second chapter - will be there at the end of the book also
if re.search(r'back-matter.pdf', chapterLink):
if len(chapters)<2:
continue
chapters.append(chapterLink)
# get next page
match = re.search(r'<a href="([^"#]+)"[^>]*>Next</a>', page)
if match:
link = "http://www.springerlink.com" + match.group(1).replace("&", "&")
else:
break
if len(chapters) == 0:
error("No chapters found - bad link?")
print "found %d chapters" % len(chapters)
# setup; set tempDir as working directory
tempDir = tempfile.mkdtemp()
os.chdir(tempDir)
i = 1
fileList = list()
for chapterLink in chapters:
if chapterLink[0] == "/":
chapterLink = "http://www.springerlink.com" + chapterLink
else:
chapterLink = baseLink + chapterLink
chapterLink = re.sub("/[^/]+/\.\.", "", chapterLink)
print "downloading chapter %d/%d" % (i, len(chapters))
localFile, mimeType = geturl(chapterLink, "%d.pdf" % i)
if mimeType.gettype() != "application/pdf":
os.chdir(curDir)
shutil.rmtree(tempDir)
error("downloaded chapter %s has invalid mime type %s - are you allowed to download %s?" % (chapterLink, mimeType.gettype(), bookTitle))
fileList.append(localFile)
i += 1
if coverLink != "":
print "downloading front cover from %s" % coverLink
localFile, mimeType = geturl(coverLink, "frontcover")
if os.system("convert %s %s.pdf" % (localFile, localFile)) == 0:
fileList.insert(0, localFile + ".pdf")
if merge:
print "merging chapters"
if len(fileList) == 1:
shutil.move(fileList[0], bookTitlePath)
else:
pdfcat(fileList, bookTitlePath)
# cleanup
os.chdir(curDir)
shutil.rmtree(tempDir)
print "book %s was successfully downloaded, it was saved to %s" % (bookTitle, bookTitlePath)
log("downloaded %s chapters (%.2fMiB) of %s\n" % (len(chapters), os.path.getsize(bookTitlePath)/2.0**20, bookTitle))
else: #HL: if merge=False
print "book %s was successfully downloaded, unmerged chapters can be found in %s" % (bookTitle, tempDir)
log("downloaded %s chapters of %s\n" % (len(chapters), bookTitle))
sys.exit()
# give a usage message
def usage():
print """Usage:
%s [OPTIONS]
Options:
-h, --help Display this usage message
-l LINK, --link=LINK defines the link of the book you intend to download
-c ISBN, --content=ISBN builds the link from a given ISBN (see below)
-n, --no-merge Only download the chapters but don't merge them into a single PDF.
You have to set exactly one of these options.
LINK:
The link to your the detail page of the ebook of your choice on SpringerLink.
It lists book metadata and has a possibly paginated list of the chapters of the book.
It has the form:
http://www.springerlink.com/content/ISBN/STUFF
Where: ISBN is a string consisting of lower-case, latin chars and numbers.
It alone identifies the book you intent do download.
STUFF is optional and looks like #section=... or similar. It will be stripped.
""" % os.path.basename(sys.argv[0])
# raise an error and quit
def error(msg=""):
if msg != "":
log("ERR: " + msg + "\n")
print "\nERROR: %s\n" % msg
sys.exit(2)
return None
# log to file
def log(msg=""):
logFile = open('springer_download.log', 'a')
logFile.write(msg)
logFile.close()
# based on http://stackoverflow.com/questions/377017/test-if-executable-exists-in-python
def findInPath(prog):
for path in os.environ["PATH"].split(os.pathsep):
exe_file = os.path.join(path, prog)
if os.path.exists(exe_file) and os.access(exe_file, os.X_OK):
return exe_file
return False
# based on http://mail.python.org/pipermail/python-list/2005-April/319818.html
def _reporthook(numblocks, blocksize, filesize, url=None):
#XXX Should handle possible filesize=-1.
try:
percent = min((numblocks*blocksize*100)/filesize, 100)
except:
percent = 100
if numblocks != 0:
sys.stdout.write("\b"*70)
sys.stdout.write("%-66s%3d%%" % (url, percent))
def geturl(url, dst):
downloader = SpringerURLopener()
if sys.stdout.isatty():
response = downloader.retrieve(url, dst,
lambda nb, bs, fs, url=url: _reporthook(nb,bs,fs,url), "MUD=MP")
sys.stdout.write("\n")
else:
response = downloader.retrieve(url, dst, None, "MUD=MP")
return response
def sanitizeFilename(filename):
p1 = subprocess.Popen(["echo", filename], stdout=subprocess.PIPE)
p2 = subprocess.Popen(["iconv", "-f", "UTF-8", "-t" ,"ASCII//TRANSLIT"], stdin=p1.stdout, stdout=subprocess.PIPE)
return re.sub("\s+", "_", p2.communicate()[0].strip().replace("/", "-"))
# start program
if __name__ == "__main__":
main(sys.argv[1:])
# kate: indent-width 4; replace-tabs on;
excpected: it should downlaod the book
actual results: with command ./springer_download.py -c "978-3-662-54804-2" i get ERROR: Could not evaluate book title - bad link http://www.springerlink.com/content/978-3-662-54804-2/contents/
the test
python2 ./springer_download.py -c "978-3-662-54804-2"
does not work either
in the code above the error is in the context
match = re.search(r'<h2 class="MPReader_Profiles_SpringerLink_Content_PrimitiveHeadingControlName">([^<]+)</h2>', page)
if not match or match.group(1).strip() == "":
error("Could not evaluate book title - bad link?")
else:
bookTitle = match.group(1).strip()
print "\nThe book you are trying to download is called '%s'\n" % bookTitle
i would also be happy with alternatives like browser addons or the like. Using the example https://link.springer.com/book/10.1007/978-3-662-54805-9#toc
| |
doc_23526235
|
Example Code:
var getUserById = function (user, callback, error) {
$.support.cors = true;
var endpoint = _getApiVersion() + '/person/model/' + user.userId;
var _headers = _setHeaders(endpoint, null, user, 'GET');
$.ajax({
type: 'GET',
beforeSend: function (request)
{
request.setRequestHeader("api-key", _headers['api-key']);
request.setRequestHeader("timestamp", _headers['timestamp']);
request.setRequestHeader("content-md5", _headers['content-md5']);
request.setRequestHeader("content-type", _headers['content-type']);
request.setRequestHeader("signature", _headers['signature']);
request.setRequestHeader("Access-Control-Allow-Origin", "*");
},
url: _getBaseUrl() + endpoint,
data: null,
contentType: 'application/json',
dataType: 'json',
success: callback,
error: error
});
};
Thanks in advance,
Dan
A: Are you trying to get data that is not in the same domain as the requester? If that is the case the only option is to proxy the original request via a service so XMLHttpRequest has access to it.
A: "Access-Control-Allow-Origin" is a response header, not a request header. It is something that the server should send back to IE as part of the response.
If that still doesn't work, you might want to try firing up the F12 Network tool in the IE Dev tools to see if you can get more detail into where in the process the request is failing (Ex: It might be failing on a CORS preflight OPTIONS request).
Also, Rather than using "Access-Control-Allow-Origin: *", you should use "Access-Control-Allow-Origin:app.samedomain.com" to control which domains can access the API
To read more about CORS, check http://www.w3.org/wiki/CORS
A: Aside from that, it feels like an order of operations thing. All this should be before the callbacks.
type: 'GET',
url: _getBaseUrl() + endpoint,
data: null,
contentType: 'application/json',
dataType: 'json',
| |
doc_23526236
|
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.eid_card_final, menu);
MenuItem item = menu.findItem(R.id.action_share);
myshare = (ShareActionProvider)item.getActionProvider();
String sharestate = Environment.getExternalStorageState();
RelativeLayout rlShareLayout = (RelativeLayout)findViewById(R.id.relativeLayout);
Bitmap sharebitmap = Bitmap.createBitmap(rlShareLayout.getWidth(), rlShareLayout.getHeight(), Bitmap.Config.ARGB_8888);
Canvas sharecanvas = new Canvas(sharebitmap);
rlShareLayout.draw(sharecanvas);
try{
if (Environment.MEDIA_MOUNTED.equals(sharestate)) {
Random sharerand = new Random();
int sharerandnum = sharerand.nextInt(1000);
String sharefilename = sharerandnum + ".jpeg";
sharef = new File(getExternalFilesDir(null),sharefilename);
FileOutputStream shareout = new FileOutputStream(sharef);
boolean success = sharebitmap.compress(CompressFormat.PNG, 100, shareout);
}
} catch (Exception e) {
e.printStackTrace();
}
Intent shareintent = new Intent(Intent.ACTION_SEND);
shareintent.setType("image/*");
Uri shareuri = Uri.fromFile(sharef);
shareintent.putExtra(Intent.EXTRA_STREAM, shareuri.toString());
shareintent.setData(shareuri);
myshare.setShareIntent(shareintent);
return true;
}
i am using same code (except intent part of code) to save file and it is working perfectly fine, what is strange is same code should at least save file automatically upon (if not send using ACTION_SEND) when options menu get created/loaded , but code for saving file is also not working (along with the intent part of code)and the worst part is that there is no error. i am stuck up. please guide what is going wrong
| |
doc_23526237
|
A: if($('#textbox1').val()) {
$('#textbox2').focus();
}
You can do something like this, but need to take care of edit case (if any), so the condition can be anything as per your needs.
A: Check the empty field in document.ready and focus on it with .focus().
After filling your first field check both fields and focus on empty one.So on first page load it will focus on your first field and after second load it will focus on you second field.
| |
doc_23526238
|
function max(...numbers) {
let result = -Infinity;
for (let number of numbers) {
if (number > result) result = number;
}
return result;
}
A: It is confusing at first and probably in your mind a solution would sound like this:
let result = 0;
The problem is that when we want to find the MAXIMUM value of an array we need to compare every element with each other. It is more like a "habit" that we set the MAXIMUM to -INFINITY. That simply means that the biggest element so far is the lowest possible number that we can express. Does it make sense? We simply assume that the biggest number we will every find is -Infinity. Then we compare the elements from the array with this base number(in our case -Infinity) and if we were false (and probably we were) then we replace -Infinity with the next number that's bigger than our current value. We do that for the whole range of numbers and that's how we find the Maximum element.
You can pick multiple elements as the starting point, but never pick a number entered by yourself( you should do that ONLY if the exercise asks so).
If you would pick for example:
let result = 0;
then you might have a problem. Maybe the numbers are all negative, for example [-3,-13,-5,13,-99] but you already set the biggest number to 0 so every comparation would be wrong and useless.
So, keep in mind that is a good practice, in this case, to set the base value to -Infinity or if you would like to take another approach then set the base value to the first element in the array.
A: In using this numbers to find the max of a series of numbers ,you loop through an array of numbers, each number will be compared to -infinity. And since the program is running from left to right the result will update itself each time it finds a bigger number. I tried this comparison method with an actual number.
let edge;
let array1 = [1, 2, 3, 4, 5, 6, 8, 9, 100, 200];
function maxwell(){
for(let checker of array1){
if(checker > 2)edge = checker;
}return edge;
}console.log(maxwell())
| |
doc_23526239
|
I am trying to compute the dominant eigenvector of an n x n matrix without having to get into too much heavy linear algebra. I did cursory research on determinants, eigenvalues, eigenvectors, and characteristic polynomials, but I would prefer to rely on the numPy implementation for finding eigenvalues as I believe it is more efficient than my own would be.
The problem I encountered was that I used this code:
markov = array([[0.8,0.2],[.1,.9]])
print eig(markov)
...as a test, and got this output:
(array([ 0.7, 1. ]), array([[-0.89442719, -0.70710678],
[ 0.4472136 , -0.70710678]]))
What concerns me about this is that by the Perron-Frobenius theorem, all of the components of the second eigenvector should be positive (since, according to Wikipedia, "a real square matrix with positive entries has a unique largest real eigenvalue and that the corresponding eigenvector has strictly positive components").
Anyone know what's going on here? Is numPy wrong? Have I found an inconsistency in ZFC? Or is it just me being a noob at linear algebra, Python, numPy, or some combination of the three?
Thanks for any help that you can provide. Also, this is my first SO question (I used to be active on cstheory.se though), so any advice on improving the clarity of my question would be appreciated, too.
A: You are just misinterpreting eig's return. According to the docs, the second return argument is
The normalized (unit “length”) eigenvectors, such that the column
v[:,i] is the eigenvector corresponding to the eigenvalue w[i].
So the eigenvector corresponding to eigenvalue 1 is not [ 0.4472136 , -0.70710678], but [-0.70710678, -0.70710678], as can be easily verified:
>>> markov.dot([ 0.4472136 , -0.70710678]) # not an eigenvector
array([ 0.21634952, -0.59167474])
>>> markov.dot([-0.70710678, -0.70710678]) # an eigenvector
array([-0.70710678, -0.70710678])
| |
doc_23526240
|
<div id="table">
<div id="user"></div>
<div id="user1"></div>
</div>
When i click a button,this happens
$("#body").append("<div id=\"user-wrap\"></div>");
$('#user').appendTo($('#user-wrap'));
$('#user1').appendTo($('#user-wrap'));
$('#user-wrap').appendTo($('#table'));
Then I apply moz-transform on user-wrap. Before I apply another transform, I have to remove this userwrap div. when I append the children of user-wrap to body again and remove the user-wrap. My transforms are not preserved. I solved this problem by storing the value in a separate variable and applying it again after removing. But the problem is when I applied the scale transforms with user-wrap on the two divs actually looked more closer. Now since I removed the user-wrap the individual user divs are apart even though I applied the transforms again. The inter-distance between children are lost.How do I solve this problem?
I am rephrasing the entire thing again, I want to apply transforms to a group of children in div and then remove the div while preserving the scale/rotate and inter-distance value between the children?
I know it is a complex question, help will be appreciated. I am hoping all the javascript samurai's and CSS ninjas could help me out here ;)
A: Against all odds:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type='text/javascript' src='jquery-1.5.1.min.js'></script>
<script type='text/javascript'>
function screwItUp() {
//EDIT: or if ($('#table div:first-child').attr('id') == 'user')
if ($('#table div:first-child').html() == 'USER') {
$('body').append('<div id=\'userWrap\'>USER-WRAP</div>');
$('#user').css('font-size',Math.floor(Math.random()*42)+'px').appendTo($('#userWrap'));
$('#user1').css('font-size',Math.floor(Math.random()*42)+'px').appendTo($('#userWrap'));
$('#userWrap').appendTo($('#table'));
} else {
$('#user').appendTo($('#table'));
$('#user1').appendTo($('#table'));
$('#userWrap').remove();
}
}
</script>
</head>
<body>
<div id="table">
TABLE
<div id="user">USER</div>
<div id="user1">USER1</div>
</div>
<button onClick='screwItUp(); ' >TOGGLE</button>
</body>
</html>
Sample: http://zequinha-bsb.int-domains.com/togglewrap.html
| |
doc_23526241
|
Is there a way to use information about the only master who still has the status of the cluster, and retrieve the Quorum between the three masters on that state? I recreated this scenario, but the cluster becomes unavailable, and I can no longer access the Etcd pods of any of the 3 masters, because those pods fail with an error. Moreover, Etcd itself becomes read-only and it is impossible to add or remove members of the cluster, to try to perform manual interventions.
Tips? Thanks to all of you
A: This is documented here. There's also another guide here
You basically have to backup your cluster and create a brand new one.
| |
doc_23526242
|
Because i have see with @solana/web3.js i can do transaction().add(...) but not with spl-token im block with the "connection" argument
A: You can do something like this
manualTransaction
.add(
SystemProgram.transfer({
fromPubkey: fromKeypair.publicKey,
toPubkey: toKeypair.publicKey,
lamports: 0.1 * LAMPORTS_PER_SOL,
})
)
.add(
SystemProgram.transfer({
fromPubkey: fromKeypair.publicKey,
toPubkey: toKeypair.publicKey,
lamports: 1 * LAMPORTS_PER_SOL,
})
);
This will allow you to send multiple instructions at once which will give you an output like in the below image
alternatively, you can do it by creating messages which also acts as a transaction instruction and later populate with
Transaction.populate(messages, [
fromPublicKey.publicKey.toString(),
])
| |
doc_23526243
|
One is half black and the other is half white.
I want to use a different one for the apps title bars depending on the darkness of the users "Accent Colour" in Windows 10.
I can get the colour in ABGR format by checking the "AccentColor" registry value at "Software\Microsoft\Windows\DWM" and with a bit of bit-shifting I can get it into RGB.
I was going to write a function that calculated the brightness/darkness of this value and choose the correct icon based on this but I noticed that when I was changing my Accent Colour and debugging the app the text in the title bar would be either black or white depending on the Accent Colour. It was doing the same kind of thing I want to do for my icons, so I thought that if I could read that title bar text colour value from somewhere that would save me writing a function.
Is there a way to get at this value in a vb.net application?
| |
doc_23526244
|
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>
<script type="text/javascript">
$(window).on('load',function(){
$('#myModal').modal('show');
});
</script>
<script>
$( document ).ready(function () {
$("#vote").click(function (e) {
var poll_id = $('input[name=pollID]', '#myForm').val();
var poll_option_id = $('input[name=voteOpt]:checked', '#myForm').val() ;
//alert(poll_id + "AND" + poll_option_id);
$.ajax({
type: "POST",
url: "http://localhost/poll/index.php/form/poll",
data: {poll_id: poll_id, poll_option_id: poll_option_id},
dataType: "json",
success: function(data) {
alert(data);
}, error: function() {
alert("ERROR");
}
});
});
});
</script>
And I have the following inside poll function in form controller
public function poll() {
$pollid = $this->input->post('pollID');
$voteData = array(
'poll_id' => $pollid,
'poll_option_id' => $this->input->post('voteOpt')
);
$voteSubmit = $this->modal->vote($voteData);
if($voteSubmit){
echo 'Your Vote Has Been Submitted successfully.';
}else{
echo 'You Had Already Voted.';
}
}
Now the thing is that, modal is executing perfectly on page load. But ajax is not working neither success part is executing nor error. Also on uncommenting the alert before ajax, correct values are alerted. I cannot figure the error.
Please help
A: I can see there are many javascript libraries included. Very sure some of them are conflicting.
Try this before $(document).ready():-
$.noConflict();
After looking at your form controller code, I can see you are just returning a text. So ajax dataType should be HTML and not json. dataType parameter is to define the type of return value.
I can only see this one wrong point in your code. Your console response status is also fine, which means it is the dataType which is wrong.
dataType = The data type expected of the server response.
dataType:'html'
A: For Example.
See you can check is you script is actually sending post values or not these way.
In you console > Network Tab. You can view which post values are sent as POST.
Now I had code in PHP Codeigniter and for me following code worked fine.
$("#username").keyup(check_if_username_exists);
function check_if_username_exists() {
var username = $("#username").val();
var sRet = false;
$.ajax(
{
type:"post",
async: false,
url: "<?php echo site_url('distributor/tenant/check_username_exists'); ?>",
data:{ username:username},
success:function(response)
{
var parent_fieldset = $("#username").parents('fieldset');
$("#username").parent().addClass('has-error');
if (response == "true")
{
$('#span').html('<span style="color: #0fa7b5;">'+"Login Username"+"</span>");
$("#username").removeClass('input-error');
$("#username").parent().removeClass('has-error');
console.log('Success! This Username is available');
hideToastr();
sRet = true;
}
else
{
show_error("Error","Oops! This Username is already taken");
$("#username").addClass('input-error');
$('#span').html('<span style="color:red;">Username already Exists!</span>');
console.log('Oops! This Username is already taken');
sRet = false;
}
}
});
console.log("End Of Username Exists " + sRet);
return sRet;
}
Also there is third party application POSTMAN which will help your debug your application. It allows you to sent post data with form values.
Update
Also I think you might have multiple JS files include issue or problem with the order they are placed. FYI I used only bootstrap.js and jquery.min.js and everything worked fine. So try removing
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>
UPDATE 2 :
Now for your controller I don't see where you encode or decode your json data.
If Your are sending the values as JSON POST to your controller then you must decode it.
First Check is you are getting JSON data in your controller.
If its working fine, then try for second step.
Step 1:
public function poll() {
$polldata = json_decode($_POST);
echo $polldata;
}
Step 2:
public function poll() {
$polldata = json_decode($_POST);
echo $polldata;
$pollid = $polldata->pollID;
$voteData = array(
'poll_id' => $pollid,
'poll_option_id' => $polldata->pollID->voteOpt
);
$voteSubmit = $this->modal->vote($voteData);
if($voteSubmit){
echo 'Your Vote Has Been Submitted successfully.';
}else{
echo 'You Had Already Voted.';
}
}
Let me know if you face any issues.
A: Your pool if should be like
if($voteSubmit){
echo json_encode(array('msg' =>'Your Vote Has Been Submitted successfully.'));
}else{
echo json_encode(array('msg' =>'You Had Already Voted.'));
}
and ur ajax success should be like
success: function(data) {
alert(data.msg);
},
error: function() {
alert("ERROR");
}
A: //change your Poll function
public function poll() {
$this->output->set_content_type('application/json');
$pollid = $this->input->post('pollID');
$voteData = array(
'poll_id' => $pollid,
'poll_option_id' => $this->input->post('voteOpt')
);
$voteSubmit =$this->modal->vote($voteData);
if($voteSubmit){
$this->output->set_output(json_encode(array('msg' => 'Your Vote Has Been Submitted successfully.')));
}else{
$this->output->set_output(json_encode(array('msg' => 'You Had Already Voted.')));
}
}
And a small change in success callback of Ajax
success: function(data) {
alert(data.msg);
//option to view data in console log
console.log(data);
},
| |
doc_23526245
|
e.g.
If the following stored proc is executed then an error message like "Executed as user: NT AUTHORITY\NETWORK SERVICE. Start [SQLSTATE 01000] (Message 0) Invalid object name 'NonExistentTable'. [SQLSTATE 42S02] (Error 208). The step failed." with no indication where exactly the failure occured.
CREATE PROCEDURE TestSpLogging AS
BEGIN
PRINT 'Start'
SELECT * FROM NonExistentTable
PRINT 'End'
END
What's the best way to expose this information?
A: Using the approach detailed at http://www.sommarskog.se/error_handling_2005.html seems to be working sufficiently so far. It has only required an update to the top level stored procedure and will output the name of the stored procedure that failed and the line number to SQL agent.
The output error will look like this:
Executed as user: NT AUTHORITY\NETWORK SERVICE. *** [InnerInnerStoredProc2], 5. Errno 208: Invalid object name 'NonExistentTable'. [SQLSTATE 42000] (Error 50000) Start [SQLSTATE 01000] (Error 0). The step failed.
Summary of steps:
Create the following error handler stored procedure:
CREATE PROCEDURE error_handler_sp AS
DECLARE @errmsg nvarchar(2048),
@severity tinyint,
@state tinyint,
@errno int,
@proc sysname,
@lineno int
SELECT @errmsg = error_message(), @severity = error_severity(), -- 10
@state = error_state(), @errno = error_number(),
@proc = error_procedure(), @lineno = error_line()
IF @errmsg NOT LIKE '***%' -- 11
BEGIN
SELECT @errmsg = '*** ' + coalesce(quotename(@proc), '<dynamic SQL>') +
', ' + ltrim(str(@lineno)) + '. Errno ' +
ltrim(str(@errno)) + ': ' + @errmsg
RAISERROR(@errmsg, @severity, @state)
END
ELSE
RAISERROR(@errmsg, @severity, @state)
go
Wrap the top level stored proc in a try catch as follows
BEGIN TRY
SET NOCOUNT ON
SET XACT_ABORT ON
EXEC InnerStoredProc1
EXEC InnerStoredProc2
END TRY
BEGIN CATCH
IF @@trancount > 0 ROLLBACK TRANSACTION
EXEC error_handler_sp
RETURN 55555
END CATCH
A: One way to do this would be add some error handling to the stored procedure. Here is a simple method we use here is something like this
declare
@Error int
,@ErrorMsg varchar(1000)
,@StepName varchar(500)
,@ProcedureName sysname
,@dtDateTime datetime
select @ProcedureName = object_name(@@procid)
begin try
select @StepName = 'Step 01: Select from table
PRINT 'Start'
SELECT * FROM NonExistentTable
PRINT 'End'
end try
begin catch
select @Error = @@ERROR
set @ErrorMsg = @ProcedureName + ' Error: ' + @StepName
+ ', dbErrorNbr:' + IsNull(convert(varchar(10),@Error),'Null')
raiserror (@ErrorMsg, 16, 1) with nowait
end catch
| |
doc_23526246
|
How can I filter Binding source or binding list. with a textbox text ?
I meam while I am typing in a textbox my grid is filtering with a %Like method not (=,equal)method.
thanks.
A: I use delegate for this problem. Some code like bellow
_List = _List.FindAll(
delegate(MyEntity entity)
{
return entity.Title.Contains(TXT_Title.Text);
}
);
Gview.DataSource = _List ;
A: You may want to use CollectionViewSource class to enable filtering.
See here
| |
doc_23526247
|
this is the html code for table
<table cellpadding="0" cellspacing="0" border="0" class="table table-bordered table-striped tblquick " id="Phone_Table">
<thead class="font-weight-light">
<tr>
<th width="100px"> Numbers</th>
<th width="100px">Edit</th>
<th width="100px">Delete</th>
</tr>
</thead>
<tbody id="Phone_TableBody">
@foreach (var item in Model.NumberList)
{
<tr>
<td width="100px" style="font:small">@item.PHONE_NUMBER</td>
<td width="100px">
<a class="Update" href="#">Update</a>
</td>
<td width="100px"><a href="#">Delete</a></td>
</tr>
}
</tbody>
</table>
this is the scripts which im using to fix the datatable header and for datatable
@section scripts{
<script src="~/Scripts/DataTables/jquery.datatables.js"></script>
<script src="~/Scripts/DataTables/datatables.bootstrap.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/fixedheader/3.1.5/js/dataTables.fixedHeader.min.js">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js">
<link rel="stylesheet" type="text/css" href="https://code.jquery.com/jquery-3.3.1.js">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/fixedheader/3.1.5/css/fixedHeader.dataTables.min.css">
<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
this is the datatable code for
var table = $('#Phone_Table').DataTable({
"bAutoWidth": false,
"bScrollCollapse": true,
"responsive": true,
"fixedHeader": true,
"searching": true,
"bDestroy": true,
"dom": "<'row'<'col-lg-12'tr>>" +
"<'row'<'col-lg-3'l><'col-lg-12'p>>",
"oLanguage": {
"sLengthMenu": "_MENU_ ",
"fixedHeader": true,
"fixedHeader": {
header: true,
}
},
});
}
A: Your js and css import are messed up
You are importing js file in css link
eg:
<link rel="stylesheet" type="text/css" href="https://code.jquery.com/jquery-3.3.1.js">
Here is the Datatable doc for fixed header
also working fiddle
To start with just replace your css and js in script section with this
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/fixedheader/3.1.5/css/fixedHeader.dataTables.min.css">
<script src="https://code.jquery.com/jquery-3.3.1.js" type="text/javascript"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js" type="text/javascript"></script>
<script src="https://cdn.datatables.net/fixedheader/3.1.5/js/dataTables.fixedHeader.min.js" type="text/javascript"></script>
| |
doc_23526248
|
I'm using sqlmembership provider. Currently I'm getting the Facebook user's full name and using it as the username. But the problem I'm having is if 2 people have the same name it won't register the second user.
How should I handle the username? I'm thinking append the Facebook id then truncate when using the username in the site? A bit ugly but can't think of a better way.
Any advice?
A: You would need the facebook ID; you could store it in session, or create a custom IPrincipal and/or IIdentity and store it with the user info.
HTH.
A: Consider creating a custom Sql Membership Provider, i am using that scheme myself for my application, that way you have a fine grain control of the way you wanna store your data.
Have a look at
http://www.asp.net/general/videos/how-do-i-create-a-custom-membership-provider
&
http://www.asp.net/general/videos/how-do-i-create-a-custom-profile-provider
A: why use something that is likely to change (the persons name). people get married, or put silly nicknames for themselves which some people change frequently.
why not use just the ID? you can always make another table (outside of SqlMembership) to store the most recent name for that user
A: I did this a while ago.
This is my table:
FacebookUniqueID BIGINT, PRIMARY KEY
FacebookEmail NVARCHAR(100), NULL
I also store other things for auditing, but that is the key info.
Now, you will always get the Facebook user id. But you won't always get the user's email address - because they can deny access - hence I allow NULLs.
The reason I store email is that Unique ID is not enough to marry the user up to the user in your system.
In the SqlMembershipProvider, the username is normally the email. So I use the "FacebookEmail" field to link the user.
If they don't allow you their email address, you're not going to be able to perform a single sign on (e.g auto sign them into your website when they are authenticated into Facebook).
But at least if they eventually grant you the permission, you can update the email field in your DB and then perform the single sign on.
| |
doc_23526249
|
I need to create a form that is based upon a collection. Eg it might look like this:
product Price
Item 1 [textbox]
Item 2 [textbox]
[submit button]
where "item" is pulled from the database and textbox allows users to update the price.
essentially this is a type of datagrid but i don't want webforms style update each row one at a time i need to update the entire set of text boxes in one post.
Ideally I don't want a javascript based solution as it has to work without javascript.
Is this possible in MVC or should I stick to webforms (where I could do this in a repeater by iterating through he repeater items on postback)
A: I wrote blog entry about it: ASP.NET MVC - Binding model to a list
To summarize:
For every row you have to generate inputs with proper prefixes. Sample:
<% foreach (var item in Model)
{ %>
<tr>
<td>
<%= Html.Hidden("contacts[" + i + "].ID", item.ID)%>
<%= Html.TextBox("contacts[" + i + "].Name", item.Name)%>
</td>
<td>
<%= Html.TextBox("contacts[" + i + "].Surname",item.Surname)%>
</td>
<td>
<%= Html.TextBox("contacts[" + i + "].Phone",item.Phone)%>
</td>
</tr>
<%
i++;
} %>
And then in controller:
[HttpPost]
public ActionResult List(IEnumerable<Contact> contacts)
{
//Here we have populated contact list, contacs parameter is filled with data from form. You save it here to your repository.
return RedirectToAction("List");
}
| |
doc_23526250
|
*
*the word starts with the uppercase vowel or consonant
*the length is 2 or more symbols (of the whole word)
*there is should not be more than two vowels or consonants in a row
Aakemenkyu
Klepathass
Waknampite
Flaetobsak
Oladkinqyt
Mmalinnetj
etc
these are words 1
[A-Z](([aeiouy]|[bcdfghjklmnpqrstvwxz]){1,2})*
this is regex 1
This regex doesn't work and i have next words generated by my code logic:
Ijythlzuoe
Tervkpxyib
Ifuemkoeui
Mqjtobojex
Ephyrjiuau
these are words 2
for example, in the word Ijythlzuoe there is thl (consonants repeating 3 times in a row) and uoe (vowels repeating)
Help, please.
A: I think by "generates" you actually want to say "matches".
You can use this regex to validate 1-2 consonants followed by 1-2 vowels, and vice versa:
/^(([aeiouy]){1,2})?(([bcdfghjklmnpqrstvwxz]){1,2}([aeiouy]){1,2})*(([bcdfghjklmnpqrstvwxz]){1,2})?$/i
Test case using JavaScript, but this regex should work in any language:
const regex = /^(([aeiouy]){1,2})?(([bcdfghjklmnpqrstvwxz]){1,2}([aeiouy]){1,2})*(([bcdfghjklmnpqrstvwxz]){1,2})?$/i;
[
'Aakemenkyu',
'Klepathass',
'Waknampite',
'Flaetobsak',
'Oladkinqyt',
'Mmalinnetj',
'Ijythlzuoe',
'Tervkpxyib',
'Ifuemkoeui',
'Mqjtobojex',
'Ephyrjiuau'
].forEach(str => {
console.log(str + ' => ' + regex.test(str));
});
Output:
Aakemenkyu => true
Klepathass => true
Waknampite => true
Flaetobsak => true
Oladkinqyt => true
Mmalinnetj => true
Ijythlzuoe => false
Tervkpxyib => false
Ifuemkoeui => false
Mqjtobojex => false
Ephyrjiuau => false
Explanation:
*
*^ - anchor at start of string
*( - start of group #1 (could be made a non-capturing group (?:...))
*
*([aeiouy]){1,2} - one to two vowels
*)? - end of group #1, ? makes this optional
*( - start of group #2
*
*([bcdfghjklmnpqrstvwxz]){1,2} - one to two consonants
*([aeiouy]){1,2} - one to two vowels
*)* - end of group #2, zero to multiple repetitions
*( - start of group #3
*
*([bcdfghjklmnpqrstvwxz]){1,2} - one to two consonants
*)? - end of group #3, ? makes this optional
*$ - anchor at end of string
*use the i flag to ignore case
A: You can try:
^(?=[A-Z][a-z]*$)(?i)(?!.*[aeiouy]{3}|.*[^aeiouy\n]{3})[a-z]+$
See the online demo
*
*^ - Start string anchor.
*(?=[A-Z][a-z]*$) - Positive lookahead to start a string with a uppercase alpha while remainder is lowercase upto end.
*(?i) - Inline modifier to match remainder case-insensitive.
*(?! - Open negative lookahead:
*
*.*[aeiouy]{3} - Match upto any three consecutive characters from class.
*| - Or:
*.*[^aeiouy\n]{3} - Match upto any three consecutive characters not in class.
*) - Close negative lookahead.
*[a-z]+ - 1+ characters from a-z (case-insensitive).
*$ - End string anchor.
A: The regex, (?=[A-Z][A-Za-z])(?i)(?!.*[aeiouy]{3}|.*[^aeiouy]{3})[a-z]+ should meet your requirement.
Explanation of the regex from regex101:
Demo:
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) {
Stream.of("Aakemenkyu",
"Klepathass",
"Waknampite",
"Flaetobsak",
"Oladkinqyt",
"Mmalinnetj",
"Ijythlzuoe",
"Tervkpxyib",
"Ifuemkoeui",
"Mqjtobojex",
"Ephyrjiuau").forEach( s -> {
System.out.println(s + " => " + s.matches("(?=[A-Z][A-Za-z])(?i)(?!.*[aeiouy]{3}|.*[^aeiouy]{3})[a-z]+"));
});
}
}
Output:
Aakemenkyu => true
Klepathass => true
Waknampite => true
Flaetobsak => true
Oladkinqyt => true
Mmalinnetj => true
Ijythlzuoe => false
Tervkpxyib => false
Ifuemkoeui => false
Mqjtobojex => false
Ephyrjiuau => false
| |
doc_23526251
|
For example:
public void showError(final String Error_Msg) {
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(common_provider.this, Error_Msg, Toast.LENGTH_LONG).show();
}
});
}
A: Yes, you can use static functions.
Create Class, for example CommonFucntions.class
CommonFunctions.class
public class CommonFunctions {
public static void showError(final Activity activity, final String Error_Msg) {
activity.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(activity, Error_Msg, Toast.LENGTH_LONG).show();
}
});
}
And then, whereever you want, you can use this function, by calling CommonFunctions.showError(this, "Sample error");
A: Extend Application class for that: https://www.mobomo.com/2011/05/how-to-use-application-object-of-android/
| |
doc_23526252
|
<div id="#myCarousel" class="carousel slide" data-ride="carousel">
<ol class="carousel-indicators">
<li data-target="#myCarousel" data-slide-to="0" class="car-btn active"></li>
<li data-target="#myCarousel" data-slide-to="1" class="car-btn"></li>
<li data-target="#myCarousel" data-slide-to="2" class="car-btn"></li>
<li data-target="#myCarousel" data-slide-to="3" class="car-btn"></li>
</ol>
<div class="carousel-inner" role="listbox">
<div class="carousel-item item active">
<img class="d-block img-fluid" src="<?php echo base_url('assets/images/home/slider-1/1-medium.jpg'); ?>" alt="Slide - 01">
</div>
<div class="carousel-item item">
<img class="d-block img-fluid" src="<?php echo base_url('assets/images/home/slider-1/2-medium.jpg'); ?>" alt="Slide - 02">
</div>
<div class="carousel-item item">
<img class="d-block img-fluid" src="<?php echo base_url('assets/images/home/slider-1/3-medium.jpg'); ?>" alt="Slide - 03">
</div>
<div class="carousel-item item">
<img class="d-block img-fluid" src="<?php echo base_url('assets/images/home/slider-1/4-medium.jpg'); ?>" alt="Slide - 04">
</div>
</div>
<a class="carousel-control left" href="#myCarousel" data-slide="prev" style="display:none;">‹</a>
<a class="carousel-control right" href="#myCarousel" data-slide="next" style="display:none;">›</a>
</div>
With the javascript:
$('#myCarousel').carousel({
interval: 4000,
pause: false,
wrap: true
});
The carousel works, it slides automatically, but nothing happens when you click on the indicators, though it does change classes to active when the image change. I'm hiding them, but the prev and next also are not working.
UPDATE:
I even tried manually firing it, but still nothing:
$('.car-btn').click(function(){
var slideTo = $(this).attr('data-slide-to');
$('#myCarousel').carousel(slideTo);
});
| |
doc_23526253
|
Xaml
<ListView Grid.Row="0" Grid.RowSpan="4" Grid.Column="0" x:Name="lvTest" ItemsSource="{Binding}" ScrollViewer.HorizontalScrollBarVisibility="Auto" SelectionMode="Single" ScrollViewer.VerticalScrollBarVisibility="Auto" Width="630" Height="270">
<ListView.View>
<GridView>
<GridViewColumn Header="Index" DisplayMemberBinding="{Binding Path=index}" Width="100" />
<GridViewColumn Header="Name" DisplayMemberBinding="{Binding Path=c.name}" Width="100" />
<GridViewColumn Header="age" DisplayMemberBinding="{Binding Path=c.age}" Width="100" />
</GridView>
</ListView.View>
</ListView>
Code Behind
public partial class MainWindow : Window
{
List<parent> parentList;
public MainWindow()
{
InitializeComponent();
GenerateList();
lvTest.ItemsSource = parentList;
}
private void GenerateList()
{
parentList = new List<parent>();
for (int i = 0; i < 10; i++)
{
parent p = new parent();
p.index = i;
child c = new child();
c.name = "Name_" + (i + 1).ToString();
c.age = i;
parentList.Add(p);
}
}
}
Classes
public class parent
{
public int index { get; set; }
public child c { get; set; }
}
public class child
{
public string name { get; set; }
public int age { get; set; }
}
I can't display the "name" and "age" property of the child class but I have no problem in accessing the index property of the parent class.
Anyone knows how to do it?
A: It's seems you forget to "save" you child instance in parent object:
child c = new child();
c.name = "Name_" + (i + 1).ToString();
c.age = i;
p.c = c; // THIS!
| |
doc_23526254
|
;WITH rec AS (
SELECT
col1 AS root_order
,col1
,col2
,col3
,col4
,col5
,col6
,col7
,col8
,col9
FROM
TableA
UNION ALL
SELECT
rec.root_order,
TableA.col2,
TableA.col3,
TableA.col4,
TableA.col5,
TableA.col6,
TableA.col7,
TableA.col8,
TableA.col9,
rec.the_level
FROM
rec
INNER JOIN TableA on rec.Details = TableA.Orders
)
SELECT DISTINCT * FROM rec
This yields a: The statement terminated. The maximum recursion 100 has been exhausted before statement completion. error.
I have tried:
OPTION (maxrecursion 0) to let it continue. But when I do that, the query infinitely loops, so that doesn't work.
In Oracle, I can use CONNECT BY ROOT and CONNECT BY PRIOR and NOCYCLE, but I know things like that aren't available in SQL Server. So I found this MSDN link which suggest something of the form:
with hierarchy
as
(
select
child,
parent,
0 as cycle,
CAST('.' as varchar(max)) + LTRIM(child) + '.' as [path]
from
#hier
where
parent is null
union all
select
c.child,
c.parent,
case when p.[path] like '%.' + LTRIM(c.child) + '.%' then 1 else 0 end as cycle,
p.[path] + LTRIM(c.child) + '.' as [path]
from
hierarchy as p
inner join
#hier as c
on p.child = c.parent
and p.cycle = 0
)
select
child,
parent,
[path]
from
hierarchy
where
cycle = 1;
go
For finding the cycles (or avoiding them). I cannot seem to take my current query and edit it in that fashion. How can I edit my current SQL to perform the cyclic reference detection like in the MSDN article?
Some sample data as requested here in SQL FIDDLE.
A: What I normally do is pretty simple. In the anchor query (the first part of the CTE), I include a value "1 AS Level" in the select list. Then in the bottom query, I select Level + 1 as the Level, so I know what depth I'm up to. Then I can just put a sanity clause into the bottom query to limit the depth i.e. WHERE LEVEL <= 10 or whatever depth you want. But yes, you still need MAXRECURSION set to 0 if you want to go above 100 levels.
Here's an example based on AdventureWorks:
WITH Materials (BillOfMaterialsID, ProductName, ProductAssemblyID, ComponentID, [Level])
AS
(
SELECT bom.BillOfMaterialsID,
p.[Name],
bom.ProductAssemblyID,
bom.ComponentID,
1
FROM Production.BillOfMaterials AS bom
INNER JOIN Production.Product AS p
ON bom.ComponentID = p.ProductID
AND bom.EndDate IS NULL
WHERE bom.ProductAssemblyID IS NULL
UNION ALL
SELECT bom.BillOfMaterialsID,
p.[Name],
bom.ProductAssemblyID,
bom.ComponentID,
m.[Level] + 1
FROM Production.BillOfMaterials AS bom
INNER JOIN Production.Product AS p
ON bom.ComponentID = p.ProductID
INNER JOIN Materials AS m
ON bom.ProductAssemblyID = BOM.ComponentID
WHERE m.[Level] <= 5
)
SELECT m.BillOfMaterialsID,
m.ProductName,
m.ProductAssemblyID,
m.ComponentID,
m.[Level]
FROM Materials AS m
ORDER BY m.[Level], m.BillOfMaterialsID;
| |
doc_23526255
|
<Style x:Key="MenuLevel2" BasedOn="{StaticResource MetroTabItem}" TargetType="{x:Type TabItem}">
<Setter Property="mah:ControlsHelper.HeaderFontSize" Value="20" />
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="true">
<Setter Property="Foreground" Value="SteelBlue"/>
</Trigger>
<Trigger Property="IsSelected" Value="True">
<!-- Sould do the work -->
<Setter Property="Foreground" Value="SteelBlue"/>
</Trigger>
</Style.Triggers>
</Style>
The text of the header is unfortunately still the one from the theme color. Any clue?
A: Your problem lies in the Controls.TabControl.xaml of MahApps.Metro. Most of the design lies in a template. As you can see in line 227 and 274, the Foreground is not bound to any property like done with other properties like Underline or HeaderFontSize.
This means you can't style these properties explicit without creating a whole new template. Since dynamic resources are used as color a solution is to override the used resources. Here is a workaround to change the colors for a tab item like required:
<TabItem Header="TabItem1">
<TabItem.Resources>
<SolidColorBrush x:Key="AccentColorBrush" Color="SteelBlue"/>
<SolidColorBrush x:Key="HighlightBrush" Color="SteelBlue"/>
</TabItem.Resources>
</TabItem>
| |
doc_23526256
|
<?php
namespace techeventBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* FosUser
*
* @ORM\Table(name="fos_user", uniqueConstraints={@ORM\UniqueConstraint(name="UNIQ_957A6479A0D96FBF", columns={"email_canonical"}), @ORM\UniqueConstraint(name="UNIQ_957A647992FC23A8", columns={"username_canonical"}), @ORM\UniqueConstraint(name="UNIQ_957A6479C05FB297", columns={"confirmation_token"})}, indexes={@ORM\Index(name="IDX_957A647914013572", columns={"copon_id"})})
* @ORM\Entity
*/
class FosUser
{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer", nullable=false)
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="username", type="string", length=180, nullable=true)
*/
private $username;
/**
* @var string
*
* @ORM\Column(name="username_canonical", type="string", length=180, nullable=true)
*/
private $usernameCanonical;
/**
* @var string
*
* @ORM\Column(name="email", type="string", length=180, nullable=false)
*/
private $email;
/**
* @var string
*
* @ORM\Column(name="email_canonical", type="string", length=180, nullable=true)
*/
private $emailCanonical;
/**
* @var boolean
*
* @ORM\Column(name="enabled", type="boolean", nullable=true)
*/
private $enabled;
/**
* @var string
*
* @ORM\Column(name="salt", type="string", length=255, nullable=true)
*/
private $salt;
/**
* @var string
*
* @ORM\Column(name="password", type="string", length=255, nullable=false)
*/
private $password;
/**
* @var \DateTime
*
* @ORM\Column(name="last_login", type="datetime", nullable=true)
*/
private $lastLogin;
/**
* @var string
*
* @ORM\Column(name="confirmation_token", type="string", length=180, nullable=true)
*/
private $confirmationToken;
/**
* @var \DateTime
*
* @ORM\Column(name="password_requested_at", type="datetime", nullable=true)
*/
private $passwordRequestedAt;
/**
* @var array
*
* @ORM\Column(name="roles", type="array", nullable=true)
*/
private $roles;
/**
* @var string
*
* @ORM\Column(name="nom", type="string", length=255, nullable=false)
*/
private $nom;
/**
* @var string
*
* @ORM\Column(name="prenom", type="string", length=255, nullable=false)
*/
private $prenom;
/**
* @var string
*
* @ORM\Column(name="tel", type="string", length=30, nullable=true)
*/
private $tel;
/**
* @var integer
*
* @ORM\Column(name="age", type="integer", nullable=false)
*/
private $age;
/**
* @var string
*
* @ORM\Column(name="sexe", type="string", length=255, nullable=true)
*/
private $sexe;
/**
* @var string
*
* @ORM\Column(name="fonction", type="string", length=255, nullable=true)
*/
private $fonction;
/**
* @var string
*
* @ORM\Column(name="address", type="string", length=255, nullable=true)
*/
private $address;
/**
* @var string
*
* @ORM\Column(name="categorie", type="string", length=255, nullable=true)
*/
private $categorie;
/**
* @var string
*
* @ORM\Column(name="type", type="string", length=255, nullable=true)
*/
private $type;
/**
* @var string
*
* @ORM\Column(name="description", type="string", length=255, nullable=true)
*/
private $description;
/**
* @var string
*
* @ORM\Column(name="role", type="string", length=255, nullable=true)
*/
private $role;
/**
* @var \Coupon
*
* @ORM\ManyToOne(targetEntity="Coupon")
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="copon_id", referencedColumnName="id")
* })
*/
private $copon;
}
i have deleted fields in this entity and changed the default value of fields to null ('nullable = true') like this :
<?php
namespace AppBundle\Entity;
use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
/**
* FosUser
*
* @ORM\Table(name="fos_user", uniqueConstraints={@ORM\UniqueConstraint(name="UNIQ_957A6479A0D96FBF", columns={"email_canonical"}), @ORM\UniqueConstraint(name="UNIQ_957A647992FC23A8", columns={"username_canonical"}), @ORM\UniqueConstraint(name="UNIQ_957A6479C05FB297", columns={"confirmation_token"})}, indexes={@ORM\Index(name="IDX_957A647914013572", columns={"copon_id"})})
* @ORM\Entity
*/
class FosUser extends BaseUser
{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer", nullable=false)
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
protected $id;
/**
* @var string
*
* @ORM\Column(name="nom", type="string", length=255, nullable=true)
*/
protected $nom;
/**
* @var string
*
* @ORM\Column(name="prenom", type="string", length=255, nullable=true)
*/
protected $prenom;
/**
* @var string
*
* @ORM\Column(name="tel", type="string", length=30, nullable=true)
*/
protected $tel;
/**
* @var integer
*
* @ORM\Column(name="age", type="integer", nullable=false)
*/
protected $age;
/**
* @var string
*
* @ORM\Column(name="sexe", type="string", length=255, nullable=true)
*/
protected $sexe;
/**
* @var string
*
* @ORM\Column(name="fonction", type="string", length=255, nullable=true)
*/
protected $fonction;
/**
* @var string
*
* @ORM\Column(name="address", type="string", length=255, nullable=true)
*/
protected $address;
/**
* @var string
*
* @ORM\Column(name="categorie", type="string", length=255, nullable=true)
*/
protected $categorie;
/**
* @var string
*
* @ORM\Column(name="type", type="string", length=255, nullable=true)
*/
protected $type;
/**
* @var string
*
* @ORM\Column(name="description", type="string", length=255, nullable=true)
*/
protected $description;
/**
* @var string
*
* @ORM\Column(name="role", type="string", length=255, nullable=true)
*/
protected $role;
/**
* @var \Coupon
*
* @ORM\ManyToOne(targetEntity="Coupon")
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="copon_id", referencedColumnName="id")
* })
*/
protected $copon;
public function __construct()
{
parent::__construct();
// your own logic
}
}
i had those errors after updating the database schema :
In AbstractMySQLDriver.php line 112:
An exception occurred while executing 'ALTER TABLE fos_user CHANGE
username username VARCHAR(180) NOT NULL, CHANGE username_canonical
username_canonic al VARCHAR(180) NOT NULL, CHANGE email_canonical
email_canonical VARCHAR(18 0) NOT NULL, CHANGE enabled enabled
TINYINT(1) NOT NULL, CHANGE roles roles LONGTEXT NOT NULL COMMENT
'(DC2Type:array)', CHANGE nom nom VARCHAR(255) D EFAULT NULL, CHANGE
prenom prenom VARCHAR(255) DEFAULT NULL':
SQLSTATE[22004]: Null value not allowed: 1138 Utilisation incorrecte
de la valeur NULL
In PDOConnection.php line 106:
SQLSTATE[22004]: Null value not allowed: 1138 Utilisation incorrecte
de la valeur NULL
In PDOConnection.php line 104:
SQLSTATE[22004]: Null value not allowed: 1138 Utilisation incorrecte
de la valeur NULL
A: Your code is right!
Previously you haven't used FOUser class, your fos_user table have already username, emailCanonical, etc ...
Then when you extend FOSUser and update database schema, your current entity doesn't accept null value for username, etc .. (It's FOSUser logic)
Solution, you have to delete your fos_user table before updating the database schema
| |
doc_23526257
|
In Java, I want to do like this:
*
*for senti_op >= , I want the logical expression as: if ("some double value" >= senti_score)
*for < , I want if ("some double value" < senti_score)
I'm trying to form these relational expression and get their boolean result to be used later by other part of the code.
Please provide compilable Java example code. I'm trying to avoid writing lots of if-else statements using string comparison for each operator and evaluate the values and looking for small and working solution.
I'm pretty new to such things and would appreciate all your help.
A: import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class SimpleTests {
public static void main(String[] args) {
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
String exp = "some double value"+ senti_op +senti_score;
try {
System.out.println(engine.eval(exp));
} catch (ScriptException e) {
e.printStackTrace();
}
}
}
A: Not tested (with some lombok annotations and some guava)
@RequiredArgsConstructor
private static enum Operation {
LESS_OR_EQUAL("<="), GREATER_OR_EQUAL(">="),
GREATER(">"), LESS("<"), EQUALS("=");
@Getter
final String operation;
public static Operation parse(final String val) {
for(final Operation pop : values()) {
if (pop.getOperation().equals(val)) {
return pop;
}
}
return null;
}
}
public boolean handleOperation(final String senti_score, final String senti_op, final Double someDoubleVal) {
// parse the double
final Double sentiScore = Doubles.tryParse(senti_score);
// parse the operation using Operation enum
final Operation sentiOp = Operation.parse(senti_op);
// TODO: checks for nullity on both parsed value
// use a switch to compute result
switch (sentiOp) {
case LESS_OR_EQUAL:
return someDoubleVal.compareTo(sentiScore) <= 1;
case GREATER_OR_EQUAL:
return someDoubleVal.compareTo(sentiScore) >= 1;
case LESS:
return someDoubleVal.compareTo(sentiScore) < 1;
case GREATER:
return someDoubleVal.compareTo(sentiScore) > 1;
case EQUAL:
return someDoubleVal.compareTo(sentiScore) == 0;
}
throw new IllegalArgumentException("Unhandled op:" + senti_op);
}
A: In Java 7, you can avoid writing the if-else chain using the switch statement on String.
You should also look into floating point arithmetic. It does not always behave as one could expect.
public class SentiEvaluator {
public boolean evaluate(String sentiOp, String sentiScore, double otherValue) {
if (sentiOp == null) {
throw new IllegalArgumentException("Operator must be specified.");
}
if (sentiScore == null) {
throw new IllegalArgumentException("Score must be specified.");
}
double score = Double.parseDouble(sentiScore);
return evaluateJava7(score, sentiOp, otherValue);
}
private boolean evaluateJava7(double leftOp, String operator, double rightOp) {
switch (operator) {
case "=": return leftOp == rightOp;
case ">": return leftOp > rightOp;
case ">=": return leftOp >= rightOp;
case "<": return leftOp < rightOp;
case "<=": return leftOp <= rightOp;
default: throw new IllegalArgumentException("Unknown operator " + operator);
}
}
}
| |
doc_23526258
|
[CIFilter filterWithName: @"CIExposureAdjust"
keysAndValues: @"inputImage", [_imageView image], nil];
A: I was writing to your earlier post link to all filters. I will repeat: link to all filters.
And for example You need Blur effect. Blur is category and have 7 filters:
*
*CIBoxBlur
*CIDiscBlur
*CIGaussianBlur
*CIMedianFilter
*CIMotionBlur
*CINoiseReduction
*CIZoomBlur.
And etc..
A: I found the list of names in CIFilter class, core image filters. here is the link names in CIFilter and the list of the filters.
Filters
CICategoryBlur
CIBoxBlur
CIDiscBlur
CIGaussianBlur
CIMaskedVariableBlur
CIMedianFilter
CIMotionBlur
CINoiseReduction
CICategoryColorAdjustment
CIColorClamp
CIColorControls
CIColorMatrix
CIColorPolynomial
CIExposureAdjust
CIGammaAdjust
CIHueAdjust
CILinearToSRGBToneCurve
CISRGBToneCurveToLinear
CITemperatureAndTint
CIToneCurve
CIVibrance
CIWhitePointAdjust
CICategoryColorEffect
CIColorCrossPolynomial
CIColorCube
CIColorCubeWithColorSpace
CIColorInvert
CIColorMap
CIColorMonochrome
CIColorPosterize
CIFalseColor
CIMaskToAlpha
CIMaximumComponent
CIMinimumComponent
CIPhotoEffectChrome
CIPhotoEffectFade
CIPhotoEffectInstant
CIPhotoEffectMono
CIPhotoEffectNoir
CIPhotoEffectProcess
CIPhotoEffectTonal
CIPhotoEffectTransfer
CISepiaTone
CIVignette
CIVignetteEffect
CICategoryCompositeOperation
CIAdditionCompositing
CIColorBlendMode
CIColorBurnBlendMode
CIColorDodgeBlendMode
CIDarkenBlendMode
CIDifferenceBlendMode
CIDivideBlendMode
CIExclusionBlendMode
CIHardLightBlendMode
CIHueBlendMode
CILightenBlendMode
CILinearBurnBlendMode
CILinearDodgeBlendMode
CILuminosityBlendMode
CIMaximumCompositing
CIMinimumCompositing
CIMultiplyBlendMode
CIMultiplyCompositing
CIOverlayBlendMode
CIPinLightBlendMode
CISaturationBlendMode
CIScreenBlendMode
CISoftLightBlendMode
CISourceAtopCompositing
CISourceInCompositing
CISourceOutCompositing
CISourceOverCompositing
CISubtractBlendMode
CICategoryDistortionEffect
CIBumpDistortion
CIBumpDistortionLinear
CICircleSplashDistortion
CICircularWrap
CIDroste
CIDisplacementDistortion
CIGlassDistortion
CIGlassLozenge
CIHoleDistortion
CILightTunnel
CIPinchDistortion
CIStretchCrop
CITorusLensDistortion
CITwirlDistortion
CIVortexDistortion
CICategoryGenerator
CIAztecCodeGenerator
CICheckerboardGenerator
CICode128BarcodeGenerator
CIConstantColorGenerator
CILenticularHaloGenerator
CIPDF417BarcodeGenerator
CIQRCodeGenerator
CIRandomGenerator
CIStarShineGenerator
CIStripesGenerator
CISunbeamsGenerator
CICategoryGeometryAdjustment
CIAffineTransform
CICrop
CILanczosScaleTransform
CIPerspectiveCorrection
CIPerspectiveTransform
CIPerspectiveTransformWithExtent
CIStraightenFilter
CICategoryGradient
CIGaussianGradient
CILinearGradient
CIRadialGradient
CISmoothLinearGradient
CICategoryHalftoneEffect
CICircularScreen
CICMYKHalftone
CIDotScreen
CIHatchedScreen
CILineScreen
CICategoryReduction
CIAreaAverage
CIAreaHistogram
CIRowAverage
CIColumnAverage
CIHistogramDisplayFilter
CIAreaMaximum
CIAreaMinimum
CIAreaMaximumAlpha
CIAreaMinimumAlpha
CICategorySharpen
CISharpenLuminance
CIUnsharpMask
CICategoryStylize
CIBlendWithAlphaMask
CIBlendWithMask
CIBloom
CIComicEffect
CIConvolution3X3
CIConvolution5X5
CIConvolution7X7
CIConvolution9Horizontal
CIConvolution9Vertical
CICrystallize
CIDepthOfField
CIEdges
CIEdgeWork
CIGloom
CIHeightFieldFromMask
CIHexagonalPixellate
CIHighlightShadowAdjust
CILineOverlay
CIPixellate
CIPointillize
CIShadedMaterial
CISpotColor
CISpotLight
CICategoryTileEffect
CIAffineClamp
CIAffineTile
CIEightfoldReflectedTile
CIFourfoldReflectedTile
CIFourfoldRotatedTile
CIFourfoldTranslatedTile
CIGlideReflectedTile
CIKaleidoscope
CIOpTile
CIParallelogramTile
CIPerspectiveTile
CISixfoldReflectedTile
CISixfoldRotatedTile
CITriangleKaleidoscope
CITriangleTile
CITwelvefoldReflectedTile
CICategoryTransition
CIAccordionFoldTransition
CIBarsSwipeTransition
CICopyMachineTransition
CIDisintegrateWithMaskTransition
CIDissolveTransition
CIFlashTransition
CIModTransition
CIPageCurlTransition
CIPageCurlWithShadowTransition
CIRippleTransition
CISwipeTransition
A: May be you can try following method of CIFilter class
+ (NSArray *)filterNamesInCategory:(NSString *)category
A: In Swift (4.2, at the time of writing this), you can use this code to get all filter names:
For filters in a specified category:
CIFilter.filterNames(inCategory: "Name_of_the_category")
For filters in specified categories:
CIFilter.filterNames(inCategories: ["Name_of_the_category_1", "Name_of_the_category_2"])
For filters in all categories, just pass nil either in inCategory or inCategories:
CIFilter.filterNames(inCategory: nil)
or
CIFilter.filterNames(inCategories: nil)
All the functions above returns an Array of the filter names in String values:
[
"CIAccordionFoldTransition",
"CIAdditionCompositing",
"CIAffineClamp",
"CIAffineTile",
"CIAffineTransform",
"CIAreaAverage",
"CIAreaHistogram"...
]
A: All you need to do is ask CIFilter for the filter names. You can then ask each filter for its attributes, which returns a dictionary that describes each input and output parameter that the filter accepts.
NSArray* filters = [CIFilter filterNamesInCategories:nil];
for (NSString* filterName in filters)
{
NSLog(@"Filter: %@", filterName);
NSLog(@"Parameters: %@", [[CIFilter filterWithName:filterName] attributes]);
}
For example, this is the output of the above code for the CIZoomBlur filter:
Filter: CIZoomBlur
Parameters: {
CIAttributeDescription = "Simulates the effect of zooming the camera while capturing the image.";
CIAttributeFilterCategories = (
CICategoryBlur,
CICategoryVideo,
CICategoryStillImage,
CICategoryBuiltIn
);
CIAttributeFilterDisplayName = "Zoom Blur";
CIAttributeFilterName = CIZoomBlur;
CIAttributeReferenceDocumentation = "http://developer.apple.com/cgi-bin/apple_ref.cgi?apple_ref=//apple_ref/doc/filter/ci/CIZoomBlur";
inputAmount = {
CIAttributeClass = NSNumber;
CIAttributeDefault = 20;
CIAttributeDescription = "The zoom-in amount. Larger values result in more zooming in.";
CIAttributeDisplayName = Amount;
CIAttributeIdentity = 0;
CIAttributeMin = 0;
CIAttributeSliderMax = 200;
CIAttributeSliderMin = 0;
CIAttributeType = CIAttributeTypeDistance;
CIUIParameterSet = CIUISetBasic;
};
inputCenter = {
CIAttributeClass = CIVector;
CIAttributeDefault = "[150 150]";
CIAttributeDescription = "The x and y position to use as the center of the effect.";
CIAttributeDisplayName = Center;
CIAttributeType = CIAttributeTypePosition;
CIUIParameterSet = CIUISetBasic;
};
inputImage = {
CIAttributeClass = CIImage;
CIAttributeDescription = "The image to use as an input image. For filters that also use a background image, this is the foreground image.";
CIAttributeDisplayName = Image;
CIUIParameterSet = CIUISetBasic;
};
outputImage = {
CIAttributeClass = CIImage;
};
}
Most of the time, though, you'll probably just use the docs.
A: NSLog(@"Distortion: %@", [CIFilter filterNamesInCategory:kCICategoryDistortionEffect]);
NSLog(@"Blurs: %@", [CIFilter filterNamesInCategory:kCICategoryBlur]);
NSLog(@"Color effects: %@", [CIFilter filterNamesInCategory:kCICategoryColorEffect]);
NSLog(@"Color adjustment: %@", [CIFilter filterNamesInCategory:kCICategoryColorAdjustment]);
NSLog(@"Built-in effects: %@", [CIFilter filterNamesInCategory:kCICategoryBuiltIn]);
A: iOS 14, Swift 5
Must confess not easy to read, but an answer that is comparable to the first one on Objective C.
for filtername in filters {
print("filter \(filtername)")
print("attributes \(CIFilter.init(name: filtername)?.attributes.keys.description)")
}
Produces this ...
filter CIAccordionFoldTransition
attributes Optional("[\"inputImage\", \"CIAttributeFilterDisplayName\", \"inputTargetImage\", \"CIAttributeFilterAvailable_iOS\", \"CIAttributeFilterAvailable_Mac\", \"inputNumberOfFolds\", \"inputFoldShadowAmount\", \"inputBottomHeight\", \"CIAttributeReferenceDocumentation\", \"inputTime\", \"CIAttributeFilterCategories\", \"CIAttributeFilterName\"]")
filter CIAdditionCompositing
attributes Optional("[\"CIAttributeFilterCategories\", \"CIAttributeFilterName\", \"CIAttributeFilterDisplayName\", \"inputImage\", \"CIAttributeReferenceDocumentation\", \"CIAttributeFilterAvailable_iOS\", \"CIAttributeFilterAvailable_Mac\", \"inputBackgroundImage\"]")
So the info is there in these long strings, you just need to pick it out :)
A: Noah Gilmore has a very handy filter tool to demo and document almost all cifilters & filter parms..
See on the app store 'CIFilter.io'. He also has the same on the web site https://cifilter.io
A: iOS 14, Swift 5
Here you can find also array of the CIFilter functions which is supported with the protocol.
CIFilter.hueSaturationValueGradient(),
CIFilter.linearGradient(),
CIFilter.radialGradient(),
CIFilter.smoothLinearGradient(),
CIFilter.sharpenLuminance(),
CIFilter.unsharpMask(),
CIFilter.dotScreen(),
CIFilter.hatchedScreen(),
CIFilter.lineScreen(),
CIFilter.bicubicScaleTransform(),
CIFilter.edgePreserveUpsample(),
CIFilter.keystoneCorrectionCombined(),
CIFilter.keystoneCorrectionHorizontal(),
CIFilter.keystoneCorrectionVertical(),
CIFilter.lanczosScaleTransform(),
CIFilter.perspectiveCorrection(),
CIFilter.perspectiveRotate(),
CIFilter.perspectiveTransform(),
CIFilter.perspectiveTransformWithExtent(),
CIFilter.straighten(),
CIFilter.accordionFoldTransition(),
CIFilter.barsSwipeTransition(),
CIFilter.copyMachineTransition(),
CIFilter.disintegrateWithMaskTransition(),
CIFilter.dissolveTransition(),
CIFilter.flashTransition(),
CIFilter.modTransition(),
CIFilter.pageCurlTransition(),
CIFilter.pageCurlWithShadowTransition(),
CIFilter.rippleTransition(),
CIFilter.swipeTransition(),
CIFilter.additionCompositing(),
CIFilter.colorBlendMode(),
CIFilter.colorBurnBlendMode(),
CIFilter.colorDodgeBlendMode(),
CIFilter.darkenBlendMode(),
CIFilter.differenceBlendMode(),
CIFilter.divideBlendMode(),
CIFilter.exclusionBlendMode(),
CIFilter.hardLightBlendMode(),
CIFilter.hueBlendMode(),
CIFilter.lightenBlendMode(),
CIFilter.linearBurnBlendMode(),
CIFilter.linearDodgeBlendMode(),
CIFilter.luminosityBlendMode(),
CIFilter.maximumCompositing(),
CIFilter.minimumCompositing(),
CIFilter.multiplyBlendMode(),
CIFilter.multiplyCompositing(),
CIFilter.overlayBlendMode(),
CIFilter.pinLightBlendMode(),
CIFilter.saturationBlendMode(),
CIFilter.screenBlendMode(),
CIFilter.softLightBlendMode(),
CIFilter.sourceAtopCompositing(),
CIFilter.sourceInCompositing(),
CIFilter.sourceOutCompositing(),
CIFilter.sourceOverCompositing(),
CIFilter.subtractBlendMode(),
CIFilter.colorAbsoluteDifference(),
CIFilter.colorClamp(),
CIFilter.colorControls(),
CIFilter.colorMatrix(),
CIFilter.colorPolynomial(),
CIFilter.colorThreshold(),
CIFilter.colorThresholdOtsu(),
CIFilter.depthToDisparity(),
CIFilter.disparityToDepth(),
CIFilter.exposureAdjust(),
CIFilter.gammaAdjust(),
CIFilter.hueAdjust(),
CIFilter.linearToSRGBToneCurve(),
CIFilter.sRGBToneCurveToLinear(),
CIFilter.temperatureAndTint(),
CIFilter.toneCurve(),
CIFilter.vibrance(),
CIFilter.whitePointAdjust(),
CIFilter.colorCrossPolynomial(),
CIFilter.colorCube(),
CIFilter.colorCubesMixedWithMask(),
CIFilter.colorCubeWithColorSpace(),
CIFilter.colorCurves(),
CIFilter.colorInvert(),
CIFilter.colorMap(),
CIFilter.colorMonochrome(),
CIFilter.colorPosterize(),
CIFilter.dither(),
CIFilter.documentEnhancer(),
CIFilter.falseColor(),
CIFilter.labDeltaE(),
CIFilter.maskToAlpha(),
CIFilter.maximumComponent(),
CIFilter.minimumComponent(),
CIFilter.paletteCentroid(),
CIFilter.palettize(),
CIFilter.photoEffectChrome(),
CIFilter.photoEffectFade(),
CIFilter.photoEffectInstant(),
CIFilter.photoEffectMono(),
CIFilter.photoEffectNoir(),
CIFilter.photoEffectProcess(),
CIFilter.photoEffectTonal(),
CIFilter.photoEffectTransfer(),
CIFilter.sepiaTone(),
CIFilter.thermal(),
CIFilter.vignette(),
CIFilter.vignetteEffect(),
CIFilter.xRay(),
CIFilter.bumpDistortion(),
CIFilter.bumpDistortionLinear(),
CIFilter.circleSplashDistortion(),
CIFilter.circularWrap(),
CIFilter.displacementDistortion(),
CIFilter.droste(),
CIFilter.glassDistortion(),
CIFilter.glassLozenge(),
CIFilter.holeDistortion(),
CIFilter.lightTunnel(),
CIFilter.ninePartStretched(),
CIFilter.ninePartTiled(),
CIFilter.pinchDistortion(),
CIFilter.stretchCrop(),
CIFilter.torusLensDistortion(),
CIFilter.twirlDistortion(),
CIFilter.vortexDistortion(),
CIFilter.affineClamp(),
CIFilter.affineTile(),
CIFilter.eightfoldReflectedTile(),
CIFilter.fourfoldReflectedTile(),
CIFilter.fourfoldRotatedTile(),
CIFilter.fourfoldTranslatedTile(),
CIFilter.glideReflectedTile(),
CIFilter.kaleidoscope(),
CIFilter.opTile(),
CIFilter.parallelogramTile(),
CIFilter.perspectiveTile(),
CIFilter.sixfoldReflectedTile(),
CIFilter.sixfoldRotatedTile(),
CIFilter.triangleKaleidoscope(),
CIFilter.triangleTile(),
CIFilter.twelvefoldReflectedTile(),
CIFilter.attributedTextImageGenerator(),
CIFilter.aztecCodeGenerator(),
CIFilter.barcodeGenerator(),
CIFilter.checkerboardGenerator(),
CIFilter.code128BarcodeGenerator(),
CIFilter.lenticularHaloGenerator(),
CIFilter.meshGenerator(),
CIFilter.pdf417BarcodeGenerator(),
CIFilter.qrCodeGenerator(),
CIFilter.randomGenerator(),
CIFilter.roundedRectangleGenerator(),
CIFilter.starShineGenerator(),
CIFilter.stripesGenerator(),
CIFilter.sunbeamsGenerator(),
CIFilter.textImageGenerator(),
CIFilter.blendWithAlphaMask(),
CIFilter.blendWithBlueMask(),
CIFilter.blendWithMask(),
CIFilter.blendWithRedMask(),
CIFilter.bloom(),
CIFilter.comicEffect(),
CIFilter.convolution3X3(),
CIFilter.convolution5X5(),
CIFilter.convolution7X7(),
CIFilter.convolution9Horizontal(),
CIFilter.convolution9Vertical(),
CIFilter.coreMLModel(),
CIFilter.crystallize(),
CIFilter.depthOfField(),
CIFilter.edges(),
CIFilter.edgeWork(),
CIFilter.gaborGradients(),
CIFilter.gloom(),
CIFilter.heightFieldFromMask(),
CIFilter.hexagonalPixellate(),
CIFilter.highlightShadowAdjust(),
CIFilter.lineOverlay(),
CIFilter.mix(),
CIFilter.pixellate(),
CIFilter.pointillize(),
CIFilter.saliencyMap(),
CIFilter.shadedMaterial(),
CIFilter.spotColor(),
CIFilter.spotLight(),
CIFilter.bokehBlur(),
CIFilter.boxBlur(),
CIFilter.discBlur(),
CIFilter.gaussianBlur(),
CIFilter.maskedVariableBlur(),
CIFilter.median(),
CIFilter.morphologyGradient(),
CIFilter.morphologyMaximum(),
CIFilter.morphologyMinimum(),
CIFilter.morphologyRectangleMaximum(),
CIFilter.morphologyRectangleMinimum(),
CIFilter.motionBlur(),
CIFilter.noiseReduction(),
CIFilter.zoomBlur] as [AnyObject]
| |
doc_23526259
|
The user must see that the next 3 events from today
therefore, when the date is past, the event disappears
how to do? thank you
My controller:
class AccueilController extends Controller {
public function affichePage() {
$agenda = Agenda::all()->take(3)->sortBy('date');
return view('Accueil.Page',compact('slides','agenda'));
}
}
A: Your code is not being sorted due to the way you are making your call. Here is what is happening at the moment:
$agenda = Agenda::all()
Load every agenda in the database
->take(3)
From all those agendas I loaded, take the first three.
->sortBy('date');
Sort only those three by date.
To achieve what you appear to want, judging by your request, you would call
$agenda = Agenda::where('date', '>=', $the_date)->orderBy('date', 'asc')->take(3)->get();
Where $the_date is the date you want to be the minimum. Typically, you would use a date function from the Carbon library to do this:
$the_date = \Carbon\Carbon::now();
This query is forcing the work to be done in database, with the call to get finally retrieving the results. In order, we are telling the database to:
*
*Filter all the agendas to only those with a date greater than the one we pass in
*Order the filtered set by the date, starting from the earliest
*Take the first three from that filtered set
*Return that set to the $agendas variable.
| |
doc_23526260
|
Example:
There are three categories within a portfolio to sort by: Branding (B), Identity (I) and Websites (W). The columns go up to five wide.
Initially, all display in a random order (which is good):
B B I B W
I W I W B
W I I
When choosing a sort order, the following occurs (say I choose Branding (B)):
B B B B I
W I W I W
W I I
Are there options within Isotope that allow for a "break" to occur after the selected sorting option? For example:
B B B B
I W I W I
W W I I
So, for the example above, the B's would be in their own row group, with everything else following after.
The custom layout mode for Category Row seems to provide a general direction, but I'm not sure of a way to call out the selected items and then just everything else.
| |
doc_23526261
|
Here is a copy of the anaconda command prompt so you better understand what I mean.
I have already reinstalled anaconda making sure that I select the C:\ directory, even installing offline so the computer has no acces to Z:, but the result is the same. Any ideas on how to solve it?
A: I defined a new windows PATH variable to ~\Anaconda2\Scripts. Then I can start jupyter notebook anywhere just by tiping "jupyter notebook" on the command line.
A: For MacOS, edit this file:
/Users/{your user name}/anaconda/bin/jupyter_mac.command
Original was:
DIR=$(dirname $0)<br/>
$DIR/jupyter-notebook
I added a line:
DIR=$(dirname $0)<br/>
cd /Users/{your user name}/{whatever folder you want}/<br/>
$DIR/jupyter-notebook
This way, Jupyter notebook starts directory you want. Be careful about folder names with space. Use \ before the space. For example, the Google Drive folder shoule be:
cd /Users/{your user name}/Google\ Drive/
| |
doc_23526262
|
services.AddAutoMapper(Assembly.GetExecutingAssembly());
Sadly it is part of application i don't think i can change, there is no proper overload for it (AFAIK). I need sth like this:
Mapper.Initialize(cfg =>
{
cfg.AddCollectionMappers();
}
But I don't think it can be done on default dependency injection. Sadly it is part i can't change.
I need to transform Entity to Dto -> Collection to bool (if there is specific element inside map to true otherwise false), sadly entity framework during transofrming entity to dto is changing reference toward inner entity and once again creates whole list instead of using existing one.
If it's not understandable -> my issue is really similiar to this: https://github.com/AutoMapper/AutoMapper/issues/3320
I've tried using "UseDesintationValue() -> it doesnt work on lists.
That's why I'm trying to same result with Automapper.Collection which should fix my issue.
| |
doc_23526263
|
public static void ResultsData()
{
const string url = "https://example.com";
const string rowXPath = "//*[@class=\"result\"]";
var web = new HtmlWeb();
var doc = web.Load(url);
HtmlNodeCollection nodes = doc.DocumentNode.SelectNodes(rowXPath);
for (int i = 0; i < nodes.Count; i++)
{
Console.WriteLine(nodes[i].InnerText);
}
}
The above seems to return the second set of results and I'm unable to figure out as to why?
I'm parsing the information from within a script:
<script>
var displayOrder = "ascending";
function NumberedOrder() {
if (displayOrder == "ascending")
{
document.getElementById("Order").innerHTML = "<span class=\"result\">1</span><span class=\"result\">2</span><span class=\"result\">3</span>";
document.getElementById("OrderButton").innerHTML = "Display ascending order";
displayOrder = "desc";
}
else
{
document.getElementById("Order").innerHTML = "<span class=\"result\">3</span><span class=\"result\">2</span><span class=\"result\">1</span>";
document.getElementById("OrderButton").innerHTML = "Display descending order";
displayOrder = "asc";
}
};
</script>
I expected to get the following results:
1
2
3
What I'm actually being given:
3
2
1
Any help would be much appreciated, I've viewed similar threads but none of helped me achieve what I'm looking for.
A: Perhaps the parsing, for some obscure implementation reason, is performed from EOF to BOF?
In which case, would the following produce the desired result?
for (int i = nodes.Count - 1; i >= 0; i--)
{
Console.WriteLine(nodes[i].InnerText);
}
This code appears to be unnecessarily complicated, but I don't see any other way around it with the information you have provided, except of course making changes to the Agility Pack's source code and compiling your own version. I have not immediately found a way to pass a parameter to DocumentNode.SelectNodes to alter what appears to be the default ordering.
| |
doc_23526264
|
function A()
{
this.a;
this.B = function()
{
this.ab ;
this.C = function()
{
this.ab = 0;
}
}
}
If the above code is correct,then
1.How do I declare an object of type B
2.Whose property is ab.A() 's or B() 's?.
3.Inside B() where does the 'this' points to.To A() Or to B()?
A: In your example, the "classes" will be instance-specific. Are you sure you want that? You might be looking for something more along the lines of:
function A() {
// ...
}
A.B = function() {
// ...
};
var one = new A();
var two = new A.B();
Although the "nested" classes won't be able to access "private members" because JavaScript doesn't have those in the first place.
As for your example:
*
*You would create an instance of A, say new A(), and access B, say new new A().B()1, or replacing new A() with a variable.
*Neither, it's an empty statement for now... but it would be a property of the B instance.
*To an instance of B (unless Function.call or Function.apply is used).
1 Yes, it works!
A: It's very unorthodox, but there's nothing stopping you from nesting constructor functions in JavaScript.
From your example, you can access the B function from an instance of A:
var someA = new A();
var someB = new someA.B();
To answer your other question:
this.B = function() {
this.ab = 0;
this.c = function() {
this.ab++;
}
}
What this refers to inside of B depends on how B is invoked. If you call B as a constructor, with the new keyword, this will be a new object inheriting from B's prototype.
If you call B without new, it will be treated as a method, and this will be the instance of A on which the method was called.
And so on with C. If C is called with new, this inside of C will be a new object inheriting from C's prototype. Or C can be a method of B, which makes a lot more sense. Is something like this what you're wanting:
function A() {
this.a;
this.B = function() {
this.ab = 0;
this.c = function() {
this.ab++;
}
}
}
var someA = new A();
var someB = new someA.B();
console.log(someB.ab); //0
someB.c();
console.log(someB.ab); //1
DEMO
Finally, note that, though nesting constructors like this isn't too common, there's nothing stopping you from adding to B's prototype just like you would any other constructor
function A() {
this.a;
this.B = function() {
this.ab = 0;
this.c = function() {
this.ab++;
}
}
this.B.prototype.foo = function() { alert("Bar " + this.ab) };
}
var someA = new A();
var someB = new someA.B();
console.log(someB.ab);
someB.c();
console.log(someB.ab);
someB.foo(); //Bar 1
Updated Demo
A: Abstract:
Calling to function without using new operator means that this will be refer to object in which that function was created.
For global variables this object is window object.
Calling using new - function behave as constructor like in classes and this refers to this instance which will been created
1.How do I declare an object of type B
First way( as a curiosity ) - by calling to A without using new operator this will be refer to windowobject and B method and all other what was declared with this leaks to global scope because A == window.A => true
A();
var b = new B; // means => new window.B //parentheses can be ommited if you invoking without arguments
alert( ab ) // alerts 'inside A' -> value from code presented below
or from instance of A:
new new A().B // means => new ( new A ).B
Be careful.
2.Whose property is ab.A() 's or B() 's?.
As above, it depends of how we'll accessing to it:
function A()
{
this.ab = "inside A";
this.B = function()
{
this.ab = "inside B";
this.c = function()
{
this.ab = "inside C";
}
}
};
Check this out
var a = new A;
a.ab // "inside A"
a.B(); // in B now 'this' refers to 'a', 'a.ab' will be replaced to 'ab' from inside 'B'
a.ab // "inside B"
but
var a = new A;
a.ab // "inside A"
var b = new a.B;
a.ab // "inside A"
b.ab // "inside B"
// and now
b.c()
b.ab // "inside C" and so on:)
3.Inside B() where does the 'this' points to.To A() Or to B()?
As above:)
| |
doc_23526265
|
Example:
hist = pygal.Bar()
hist.title = "Results of rolling numbers 0-69 100 times."
hist.x_labels = ['1', '2', '3']
hist.x_title = "Numbers Rolled"
hist.y_title = "Frequency of numbers rolled"
On line 3, I want to be able to insert numbers 1-69, or even more if i wish to change it. How can I do this easily?
I thought the range() function would work, but it didn't, unless I'm doing something wrong. Thank you
A: range() will work, but you have to convert each value to a string instead of an integer.
hist.x_labels = [ str(n) for n in range(69) ]
A: Use a list and a simple for loop, e.g.
numbers = []
for number in range(100):
numbers.append(number)
this will give you a list with all values from 0 -> 100.
as John Gordon pointed out it seems you may want to have those numbers as Strings, for that just change the third line to:
numbers.append(str(number))
| |
doc_23526266
|
foreach (var price in prices.GroupBy(x => x.Timestamp))
{
logger.LogInformation($"{price.Key.ToString("yyyy-MM-dd HH:mm:ss.fff")}");
}
2021-10-01 20:54:49.661
2021-10-01 21:00:00.356
2021-10-03 21:05:03.816
2021-10-03 21:05:15.876
2021-10-03 21:05:29.140
2021-10-03 21:05:51.356
2021-10-03 21:06:04.996
2021-10-03 21:06:15.308
2021-10-03 21:06:44.648
2021-10-03 21:06:58.521
2021-10-01 20:54:49.661
2021-10-01 21:00:00.356
2021-10-03 21:05:03.816
2021-10-03 21:05:15.876
2021-10-03 21:05:29.140
2021-10-03 21:05:51.356
2021-10-03 21:06:04.996
2021-10-03 21:06:15.308
2021-10-03 21:06:44.648
2021-10-03 21:06:58.521
On my local machine the exact same code produces the following which is correct
2021-10-01 20:54:49.661
2021-10-01 21:00:00.356
2021-10-03 21:05:03.816
2021-10-03 21:05:15.876
2021-10-03 21:05:29.140
2021-10-03 21:05:51.356
2021-10-03 21:06:04.996
2021-10-03 21:06:15.308
2021-10-03 21:06:44.648
2021-10-03 21:06:58.521
Anyone knows the reason why that happens?
A: If you mean that your first output repeats itself halfway, then something in those keys are different. You don't see all details through your ToString() format string.
Repro:
var now = DateTime.Now;
var dateTimes = new []
{
new DateTime(now.Ticks),
new DateTime(now.Ticks),
new DateTime(now.Ticks + 1),
new DateTime(now.Ticks + 2),
new DateTime(now.Ticks + 3),
};
var groupedDateTimes = dateTimes.GroupBy(x => x);
foreach (var grouped in groupedDateTimes)
{
Console.WriteLine($"{grouped.Key.ToString("yyyy-MM-dd HH:mm:ss.ffffff")} (count: {grouped.Count()})");
}
Gives:
2021-11-03 09:22:57.585592 (count: 2)
2021-11-03 09:22:57.585592 (count: 1)
2021-11-03 09:22:57.585592 (count: 1)
2021-11-03 09:22:57.585592 (count: 1)
The keys look the same, but their ticks are different. If you have DateTimes with equal ticks as you claim, then perhaps your production code just calls the method twice or otherwise duplicates the data. GroupBy() is not broken, assume your code is.
| |
doc_23526267
|
I have a Post and Comment models in my Django project. What I'm trying to do is list out all the Blog posts, and show NUMBER OF COMMENTS OF EACH POST. Please see my codes below.
models.py
class Blog(models.Model):
objects = models.Manager()
title = models.CharField(max_length=100, blank=True)
body = models.CharField(max_length=10000, blank=True)
created_at = models.DateField(auto_now_add=False)
class Comment(models.Model):
objects = models.Manager()
post = models.ForeignKey(Blog, on_delete=models.CASCADE, related_name='comment')
views.py
def main_page(request):
all_blogs = Blog.objects.all()
context = {
'blog' : blog,
}
return render(request, 'main/home.html', context)
template
{% for b in blog %}
<div>
<p>{{b.title}}</p>
<div>
{{WHERE THE NUMBER OF THIS POST'S COMMENTS IS DISPLAYED}}
</div>
</div>
{% endfor %}
All I need is the number of the comments, but have no idea how to do it. Is there a way to make this possible in the template? Or do I have to add some codes in views.py?
A: You can annotate the Blog objects with the number of related Comments with:
from django.db.models import Count
def main_page(request):
all_blogs = Blog.objects.annotate(
num_comments=Count('comment')
)
context = {
'blogs' : blogs
}
return render(request, 'main/home.html', context)
The Blog objects that arise from that queryset will have an extra attribute .num_comments with the number of related comments:
{% for blog in blogs %}
<div>
<p>{{ blog.title }}</p>
<div>
{{ blog.num_comments }}
</div>
</div>
{% endfor %}
| |
doc_23526268
|
Some background on the overall context of what I'm doing: this section of code is part of a questionnaire I'm creating.
This is the code in question:
var resultsView = {};
function sumAnswers(className) {
//some stuff here
$(className:checked).each(function() {
//some other code here to sum answers
var text = $(this).siblings('.question').text();
var answer = $(this).next('label').text();
resultsView[text] = answer;
});
}
I'm trying to add the question text and selected answer text in a key/value relationship to an object, that way I can later pass it through AJAX to a PHP file.
The problem is that when I console.log resultsView, it only adds one question/answer multiple times. Changing the operator to += isn't working either. What am I doing wrong?
A: I am unable to see such a issue could you please check it in the below jsfiddle
http://jsfiddle.net/sZYaf/19/
I have create similar code in the above specified case
$("#check").click(function(){
var resultsView = {};
$(".check:checked").each(function() {
//some other code here to sum answers
var text = $(this).siblings('.question').text();
var answer = $(this).next('label').text();
resultsView[text] = answer;
});
alert(resultsView["question1"] + resultsView["question2"] );
});
Thanks
| |
doc_23526269
|
I have a small node express api which is hosted on my Raspberry Pi which is running raspbian.
The js file is started in a cron job:
@reboot sudo /usr/bin/node /var/www/html/api/server.js &
And the API itself works fine, I can access it and it returns my requests without a problem.
But the API is also supposed to write to a log file when someone makes a request:
fs.appendFile("./ServerLog.log", "[" + dateTime + "]" + " [" + status + "] " + message + "\n", null, () => {
});
This does not work. But when I kill the process which was started through the cronjob and start it manually it creates a log.
I tried launching node with bash, i.e:
@reboot sudo bash -c "sudo /usr/bin/node /var/www/html/api/server.js &"
But that did not change anything. I also changed the output to just write "TEST" but that did not work either. I do have a shebang at the beginning of my js file : #!/usr/bin/env node
These are the lines which are printed to the syslog:
Nov 18 20:20:05 raspberrypi cron[331]: (CRON) INFO (pidfile fd = 3)
Nov 18 20:20:05 raspberrypi cron[331]: (CRON) INFO (Running @reboot jobs)
And in auth.log:
Nov 18 20:20:05 raspberrypi systemd-logind[309]: New seat seat0.
Nov 18 20:20:05 raspberrypi CRON[343]: pam_unix(cron:session): session opened for user root by (uid=0)
Nov 18 20:20:05 raspberrypi CRON[343]: pam_unix(cron:session): session closed for user root
Nov 18 20:20:05 raspberrypi sudo: root : TTY=unknown ; PWD=/root ; USER=root ; COMMAND=/usr/bin/node /var/www/html/api/server.js
Nov 18 20:20:05 raspberrypi sudo: pam_unix(sudo:session): session opened for user root by (uid=0)
A: You get a different environment in cron started jobs than you have in an interactive shell. Typically the PATH is by far not as elaborate as in an interactive shell. Easiest to fix this is to explicitly set the full path.
#!/usr/bin/env node actually uses the environment to find the executable called 'node'. Simplest is to replace it with an explicit path to node e.g. #!/usr/local/bin/node or wherever it is installed on your system. To find where it is installed: use which node in an interactive shell.
sudo is a command that lets you run a command as another user, it'll not help you as such to set PATH values in cron like you have in an interactive shell.
A: the issue is with the PATH.
for me I was using serveStatic and providing the path to the static folder like ./public. This was resolving to the wrong path. By providing complete URL i was able to resolve the issue.
You may solve the same issue with other solutions also, the point is that your code is not resolving to the write file because of PATH.
| |
doc_23526270
|
I need to write a Python code that takes all values of x<1 and apply it to "sigma", and all values of x= 1 and so on and apply it to "sigma" to get "sigma" (an array of the same length, i.e 100 values
How can I do it?
My attempt so far is:
a1 = (2*delta_c*rho_0*r_s)/(x**2-1)
b1 = (2/(np.sqrt(1-x**2)))
c1 = np.arctanh(np.sqrt((1-x)/(1+x)))
a2 = (2*delta_c*rho_0*r_s)/(1-x**2)
b2 = 2/(np.sqrt(x**2-1))
c2 = np.arctan(np.sqrt((x-1)/(1+x)))
#finding sigma(x)
for i in x:
if i<1:
sigma = a1*(1-(b1*c1))
elif i == 1:
sigma = (2*delta_c*rho_0*r_s)/3
elif i>1:
sigma = a2*(1-(b2*c2))
The problem is, if you can see in my formula for a1,b1,c1 and a2,b2,c2, there is x involved. So I need to apply the conditions for x here as well
A: You can do this pretty easily with boolean item assignment (for numpy arrays):
sigma = np.empty(x.shape)
sigma[x<1] = a1*(1-(b1*c1))
sigma[x==1] = (2*delta_c*rho_0*r_s)/3
sigma[x>1] = a2*(1-(b2*c2))
A: How about:
sigma = x
for i, xi in enumerate(x):
a1 = (2*delta_c*rho_0*r_s)/(xi**2-1)
b1 = (2/(np.sqrt(1-xi**2)))
c1 = np.arctanh(np.sqrt((1-xi)/(1+xi)))
a2 = (2*delta_c*rho_0*r_s)/(1-xi**2)
b2 = 2/(np.sqrt(xi**2-1))
c2 = np.arctan(np.sqrt((xi-1)/(1+xi)))
if xi<1:
sigma[i] = a1*(1-(b1*c1))
elif xi == 1:
sigma[i] = (2*delta_c*rho_0*r_s)/3
elif xi>1:
sigma[i] = a2*(1-(b2*c2))
| |
doc_23526271
|
id time_stamp Access Type
1001 2017-09-05 09:35:00 IN
1002 2017-09-05 11:00:00 IN
1001 2017-09-05 12:00:00 OUT
1002 2017-09-05 12:25:00 OUT
1001 2017-09-05 13:00:00 IN
1002 2017-09-05 14:00:00 IN
1001 2017-09-05 17:00:00 OUT
1002 2017-09-05 18:00:00 OUT
I tried this query below:
select *, datediff(minute, first_in, last_out) as durationfrom (
select id
, min(case when [Access Type] = 'IN' then time_stamp end) as first_in
, max(case when [Access Type] = 'OUT' then time_stamp end) as last_out
, cast(min(time_stamp) as date) as date
from Table1
group by
id
, cast(time_stamp as date)
) as SubQueriesMustBeNamed
when i try this query it shows only first in last out.
Desired Result:
id check_in check_out totalhrs check_in check_out totalhrs date
1001 09:35 12:00 2:25 13:00 17:00 2:00 2013-09-05
1002 11:00 12:25 1:25 14:00 18:00 4:00 2013-09-05
The result will be above like this . Anyone help me.. Thanks in advance
A: SQL Fiddle
MS SQL Server 2014 Schema Setup:
CREATE TABLE Table1
([id] int, [time_stamp] datetime, [AccessType] varchar(3))
;
INSERT INTO Table1
([id], [time_stamp], [AccessType])
VALUES
(1001, '2017-09-05 09:35:00', 'IN'),
(1002, '2017-09-05 11:00:00', 'IN'),
(1001, '2017-09-05 12:00:00', 'OUT'),
(1002, '2017-09-05 12:25:00', 'OUT'),
(1001, '2017-09-05 13:00:00', 'IN'),
(1002, '2017-09-05 14:00:00', 'IN'),
(1001, '2017-09-05 17:00:00', 'OUT'),
(1002, '2017-09-05 18:00:00', 'OUT')
;
Query 1:
select
id, cast(time_stamp as date) [date]
, format(max(case when in_rank = 1 then time_stamp end),'HH:mm') check_in_1
, format(max(case when in_rank = 1 then next_timestamp end),'HH:mm') check_out_1
, format(max(case when in_rank = 1 then
dateadd(ss,datediff(ss,time_stamp,next_timestamp),0) end),'HH:mm') total_hrs_1
, format(max(case when in_rank = 2 then time_stamp end),'HH:mm') check_in_2
, format(max(case when in_rank = 2 then next_timestamp end),'HH:mm') check_out_2
, format(max(case when in_rank = 2 then
dateadd(ss,datediff(ss,time_stamp,next_timestamp),0) end),'HH:mm') total_hrs_2
from (
select
id, time_stamp, AccessType, next_timestamp, next_accesstype
, dense_rank() over(partition by id, cast(time_stamp as date) order by time_stamp) in_rank
from table1 t1
outer apply (
select top(1) t2.time_stamp, t2.AccessType
from table1 t2
where t1.id = t2.id and t1.AccessType <> t2.AccessType
and cast(t1.time_stamp as date) = cast(t2.time_stamp as date)
and t1.time_stamp < t2.time_stamp
order by t2.time_stamp
) oa (next_timestamp, next_accesstype)
where AccessType = 'IN'
) d
group by id, cast(time_stamp as date)
Results:
| id | date | check_in_1 | check_out_1 | total_hrs_1 | check_in_2 | check_out_2 | total_hrs_2 |
|------|------------|------------|-------------|-------------|------------|-------------|-------------|
| 1001 | 2017-09-05 | 09:35 | 12:00 | 02:25 | 13:00 | 17:00 | 04:00 |
| 1002 | 2017-09-05 | 11:00 | 12:25 | 01:25 | 14:00 | 18:00 | 04:00 |
| |
doc_23526272
|
I am downloading PDF file after window.open() method has been called and later need to close current(new opened) tab via window.close() method.
window.close() method should run only after load event of window object is completed and PDF file is downloaded, but load event is not firing.
Here is code:
.subscribe(
(res: any) => {
if (response) {
const formData: string = response.replace(/\n/g, '');
const win: any = window.open('', '_blank'); // open new tab
win.document.write(formData);
// NOT FIRED
win.addEventListener('load', () => {
// submit form received in response
win.close(); // NOT CALLED
},
false
);
}
}
);
Note: I don't want to use setTimeout() function and call window.close() there since
the time for downloading might vary based on different factors (such as browser environment, file size and et.c.),
otherwise it's possible to solve this issue by using:
win?.setTimeout(() => {
win?.close();
}, 3000);
So, what is wrong here? Any help is appreciated.
A: Looking at your code, it looks like you are adding the load listener on window and not on win which is probably what you want.
Here is the way I normally use.
I do not have a way to test this with pdf files, but the way I download files received with an http request is by using Blob. Like this:
const blob = new Blob([res], {type : 'application/pdf'});
const url = window.URL.createObjectURL(blob);
window.open(url);
From my experience with other file types, this opens the tab, starts downloading the file and closes (while the file is still downloading).
Feel free to ask for clarification if needed!
| |
doc_23526273
|
Now I understand what the values do and that the third value is a route parameter value but this is the first time I'm seeing this kind of syntax which is really bugging me for some reason.
What I mean exactly is new {genre = genre.Name}. I've come to understand that "new" precedes object/type declaration, however, this time it's simply the "new" keyword and the curly brackets. How exactly is this processed?
A: The syntax new { prop = val } creates an anonymous type. It's essentially the same as creating an instance of a class, except you're declaring the class and the instance all in one shot. Some people think that anonymous types are not statically typed or are not type safe. This isn't true. The types of the properties are inferred from the values they are assigned. This construction is used frequently in MVC and in linq.
Note that this syntax is not specific to MVC. You can use it anywhere it's convenient. I make a fair amount of use of anonymous types in day-to-day coding.
A: It's simple.. the first parameter is the link you want to display, so genre.Name can corresponds to Rock. The second argument is the action, the third argument your Controller class. The last parameter is the route values in the form of an anonymous object (an object you will never use again, the MVC engine uses the anonymous object in this case).
So your action(method) takes a string argument.
For example:
"Home" is the link the user sees (the first argument), Home (the second argument) is the action (method) to your Controller class, and it takes a string argument.
class HomeController
{
public ActionResult GenreAction(string genre)
{
}
}
When a request is made, it becomes Home/GenreAction/genre
A: It's a C# language feature called Anonymous Type, introduced with C# 3.5 if I'm not mistaken.
| |
doc_23526274
|
But these two should be considered the same according to the manual.
`c' for bytes
`w' for two-byte words
`k' for Kilobytes (units of 1024 bytes)
I have a bunch of files that are 1.5k or so. -2048c could find these files, but -2k gave nothing.
A: This is not a bug. POSIX specifies* that find should use only whole periods when performing a comparison, with any remainder discarded. This means that -size -2k will indeed not find any file with a size between 1025 and 2047 bytes.
* Technically it is only specified for the block unit size determination; GNU find extends this to the kilobyte unit for consistency.
| |
doc_23526275
|
The code looks as following:
import React from 'react';
import { from } from 'rxjs';
import { map } from 'rxjs/operators';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
fromArray: [1, 2, 3, 4, 5]
};
}
componentDidMount() {
const observable$ = from(this.state.fromArray).pipe(
map(value => ({
observable: value + 1
}))
);
this._subscription = observable$.subscribe(
result => this.setState({...result})
)
}
componentWillUnmount() {
this._subscription.unsubscribe();
}
render() {
const { fromArray } = this.state;
return (
<ul>
{
fromArray.map((item, index) => <li key={index}>{item}</li>)
}
</ul>
)
}
}
export default App;
But, I've got the initial array in the list only.
How to make it work?
A: Here is the demo. There are 2 problems here:
*
*in map function you get an updated element of array(2, 3, 4, 5, 6). But you need to have the new array itself to be set in the state. That's why I've used reduce.
*you need to specify which part of the state you are setting. Not in this way: result => this.setState({...result}), but in this: newFromArray => this.setState({ fromArray: newFromArray })
import React from "react";
import ReactDOM from "react-dom";
import { from } from "rxjs";
import { reduce } from "rxjs/operators";
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
fromArray: [1, 2, 3, 4, 5]
};
}
componentDidMount() {
const observable$ = from(this.state.fromArray).pipe(
reduce((acc, value) => [...acc, value + 1], [])
);
this._subscription = observable$.subscribe(newFromArray => {
return this.setState({ fromArray: newFromArray });
});
}
componentWillUnmount() {
this._subscription.unsubscribe();
}
render() {
const { fromArray } = this.state;
return (
<ul>
{fromArray.map((item, index) => (
<li key={index}>{item}</li>
))}
</ul>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
| |
doc_23526276
|
JNI4NET has generated proxy class for .Net code. One of the methods accept system.Object as an input parameter.
I want to send String value as input to that method. I have wrote the below code for that-
String s = "test";
Object b = s;
system.Object object = (system.Object) b;
And passing this obj as an input to proxy method. The above code throws runtime exception java.lang.String cannot be cast to system.Object. Any help or pointers will be useful.
A: java.lang.String can be cast to java.lang.Object (though there's no reason to cast it - you can simply assign it to an Object reference as you do in - Object b = s;), not to system.Object.
I did some searching. It looks like this might help :
String s = "test";
system.String b = new system.String(s);
system.Object object = b;
Since system.String is a sub-class of system.Object, you can pass it to your test method.
| |
doc_23526277
|
Now my problem is that in GET calls json is camel cased which is good, but for POST or PUT calls json is pascal cased.
I've tried to register it in GlobalConfig or in WebApiConfig like this:
json.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
but no result.
Any help to get all calls camel cased will be much appreciated.
A: If I understand correctly then your problem is like this.
*
*If you make you API Call if you have Get API call so get CamelCased Json from Response from API.
*When you post or put data to API then it is not CamelCased. Right ?
If above is your case then It is correct behavior.
ContractResolver role is format response data not request data.
| |
doc_23526278
|
In short, what criteria needs to be in place for this for --findRelatedTests to work properly?
*
*Do the source file/test file need to be similarly named?
e.g. Page.jsx and Page.test.js
*Do the test files need to be in the same folder as the source file, or should they be placed in a separate tests folder?
I ask because I tend to follow the AirBnb project structure for my applications:
- components
- Page
- index.jsx
- style.scss
- Page.test.js
...and I'd like to know if I updated the Page component index.jsx file whether --findRelatedTests would "know" that Page.test.js is the associated test file?
| |
doc_23526279
|
root that I want to redirect to,
but I got this error :
InvalidOperationException: No page named 'Miner/MinerDetail' matches the supplied values.
I want to redirect to this page miner/MinerDetail with a model that it is minerPartsView
A:
Want to redirect to this page miner/MinerDetail with a model that it
is minerPartsView
Well, as per your shared screenshot, it appeared that, you were not able to redirect to your MinerDetails page due to two main reason.
Firstly, if your Request.IsAjaxRequest() executes then your next block will not executes, you have already returned the statements.
Second, reason you are not redirecting to the MinerDetails page in correct manner. As you haven't share your MinerDetails page details design thus I am sharing how you could redirect to a new razorpage with new object.
Model:
Let's assume, we have below model which we would like to pass from our intial page to MinerDetails page.
public class MinerCustomModel
{
public string? PowerSerialNumber { get; set; }
public string? MinerSerialNumber { get; set; }
public string? WorkerName { get; set; }
}
Note: In your scenario, model would be minerPartsView model
Intial Index/ Loading Page:
public class IndexModel : PageModel
{
private readonly ILogger<IndexModel> _logger;
public IndexModel(ILogger<IndexModel> logger)
{
_logger = logger;
}
public async Task<IActionResult> OnGet()
{
var myData = new MinerCustomModel()
{
MinerSerialNumber = "SM-001",
PowerSerialNumber = "PSN-002",
WorkerName = "Worker Name"
};
string data = System.Text.Json.JsonSerializer.Serialize(myData);
return RedirectToPage("Miner/MinerDetails", new { objectData = data });
}
}
MinerDetails Page:
public class MinerDetailsModel : PageModel
{
[BindProperty]
public MinerCustomModel? minerCustomModel { get; set; } = new MinerCustomModel();
public void OnGet(string objectData)
{
var enitity = System.Text.Json.JsonSerializer.Deserialize<MinerCustomModel>(objectData);
minerCustomModel.PowerSerialNumber = enitity.PowerSerialNumber;
minerCustomModel.MinerSerialNumber = enitity.MinerSerialNumber;
minerCustomModel.WorkerName = enitity.WorkerName;
}
}
Note: Make sure, we are defining the MinerCustomModel which should a class not pageModel with [BindProperty] which should intializing as new MinerCustomModel() to avoid null reference exception.
MinerDetailsModel Page View:
@page
@model MinerDetailsModel
<h1>Miner Details</h1>
<table class="table">
<thead>
<tr>
<th>
PowerSerialNumber
</th>
<th>
MinerSerialNumber
</th>
<th>
WorkerName
</th>
</tr>
</thead>
<tbody>
<tr>
<td>
@Model.minerCustomModel?.PowerSerialNumber
</td>
<td>
@Model.minerCustomModel?.MinerSerialNumber
</td>
<td>
@Model.minerCustomModel?.WorkerName
</td>
</tr>
</tbody>
</table>
Note: In MinerDetails view we should refer @model MinerDetailsModel page model not the MinerCustomModel or IndexModel.
Output:
| |
doc_23526280
|
I would like to add a new column to the weights dataframe that has the emergence date associated with the correct individual, so that each row has the individual ID, the emergence date for the individual, and the weights date. I can then calculate the difference in days.
I have looked at different methods for joining dataframes but can't find any for this particular function to associate new data
I would like a new column in the weights data that contains the emergence date for each individual
A: I think you're looking for merge. I've made sample dataframes similar to yours to aid the exercise.
EmDates <- as.POSIXct(c("06/28/2019", "06/29/2019", "06/30/2019"), origin = "EST", format = "%m/%d/%Y")
Ind_ID <- c(1,2,3)
Emerg <- as.data.frame(EmDates)
Emerg <- cbind(Emerg, Ind_ID)
Ind_ID <- NULL
WeighDates <- as.POSIXct(c("07/28/2019", "07/29/2019", "07/30/2019"), tz = "EST", format = "%m/%d/%Y")
Ind_ID <- c(3,2,1)
Weigh <- as.data.frame(WeighDates)
Weigh <- cbind(Weigh, Ind_ID)
Target_DF <- merge(Emerg, Weigh, by = "Ind_ID")
Alternatively the dplyr join family can help here, with a few more options. Left join will keep all the data in the left (first) dataframe, and all the matching data in the right (second) data frame. Other join types in the link above will select data differently.
library(dplyr)
EmDates <- as.POSIXct(c("06/28/2019", "06/29/2019", "06/30/2019"), origin = "EST", format = "%m/%d/%Y")
Ind_ID_Emerg <- c(1,2,3)
Emerg <- as.data.frame(EmDates)
Emerg <- cbind(Emerg, Ind_ID_Emerg)
WeighDates <- as.POSIXct(c("07/28/2019", "07/29/2019", "07/30/2019"), tz = "EST", format = "%m/%d/%Y")
Ind_ID_Weigh <- c(3,2,1)
Weigh <- as.data.frame(WeighDates)
Weigh <- cbind(Weigh, Ind_ID_Weigh)
Target_DF <- left_join(Emerg, Weigh, by = c("Ind_ID_Emerg" = "Ind_ID_Weigh"))
| |
doc_23526281
|
document.open();
document.write(ad_tag1);
document.close();
The first ad unit will render an ad with some probability or else it will fire a postmessage event to the ad unit iframe indicating there's no ad to show.
If there's an ad to show, everything's golden. However, if there's not, the ad unit will proceed to do:
document.open();
document.write(ad_tag2);
document.close();
This causes the second ad tag to render just fine. However, the problem is that Firefox seemingly can't detect when the second ad unit has loaded even though it clearly has and the spinner at the top of the page keeps spinning forever as if there's still stuff to load.
I have also tried using DOM manipulation methods such as innerHTML, but that produced the same problem. I also tried using Prototype JS's built-in update method, but that also caused the same problems.
Anyone have any ideas why Firefox is doing this? My code works perfectly on chrome..
Also, I have no control of what the ad tags are. The ad tags are third party and may as well be black boxes from my point of view as in the ad tags may contain scripts, may drop an iframe, etc.
A: I have seen this before, quite a few times. It is almost always caused by malformed HTML being written to the document, or incomplete HTML. Consider:
<html>
<div id="myadd2">
<p>Some stuff<p>
</div>
There is no closing </p> and also no closing <html> tag. This can cause Firefox to think the document is still loading. It won't complete until it receives an EOF from the server (closes connection) or it sees the closing HTML tag and a well formed HTML block.
It might be that the second add contains mismatched quotes, an unterminated html tag or mismatched tags. Run the HTML content through xmllint --html to see what it thinks of it.
| |
doc_23526282
|
Here is my code:
import csv
import requests
from bs4 import BeautifulSoup
def getData(url_to_scrap='https://www.investing.com/currencies/eur-usd-historical-data', file=None, save_file="Name.csv"):
if url_to_scrap is not None:
header = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'}
r = requests.get(url_to_scrap, headers=header)
data = BeautifulSoup(r.content, 'html.parser')
else:
data = BeautifulSoup(open(file, encoding='utf8'), 'html.parser')
table = data.find(id='curr_table')
table = table.find_all('td')
row_data = []
for row in table:
row_data.append(row.get_text('data-real-value'))
with open(save_file, 'w') as save:
for row in row_data:
writer = csv.writer(save, delimiter=';')
writer.writerow(row)
getData(save_file="EUR USD Historical Data.csv")
And the output on the CSV file:
M;a;y; ;3;1;,; ;2;0;1;7
1;.;1;2;1;8
1;.;1;1;7;2
1;.;1;2;2;0
....
What I need:
May 31, 2017;1.1218;1.1172;1.1220;1.1165;0.30%
If you check the website, everything is in a table and I need it similar in csv.
What should I change to make it work?
A: Make sub lists of length six each (= 1 row) from your row_data list (via):
with open(save_file, 'wb') as save:
writer = csv.writer(save, delimiter=';')
for row in [row_data[x:x+6] for x in xrange(0, len(row_data), 6)]:
writer.writerow(row)
#May 31, 2017;1.1242;1.1172;1.1252;1.1165;0.51%
#May 30, 2017;1.1185;1.1163;1.1207;1.1108;0.18%
#May 29, 2017;1.1165;1.1177;1.1192;1.1159;-0.16%
#...
(As noted here, xrange may need to be range if you are using Python 3; I'm on Python 2 and a beginner, so...)
A: EDIT
When you are appending the strings to the row list, append it as a list
row_data.append([row.get_text('data-real-value')])
so that you have a list of lists of strings.
see Python csv library leaves empty rows even when using a valid lineterminator for a better example.
Keep the writerows as below to print a single item per line.
with open(save_file, 'w') as save:
writer = csv.writer(save, delimiter=';')
writer.writerows(row)
since it will place the delimiter between each element in the list
| |
doc_23526283
|
For one of my cell types I have a UIPicker that appears in place of the keyboard. All works well and I have a nice animation to slide it in and out just like the keyboard. The problem is, because I added the picker as a subview the UITableViewController's view property it is possible for the user to scroll the UIPicker up and down.
I understand why this is happening (I assume the view property is assigned to the tableView property of the viewController and therefore my picker is being added on top of the tableView, which has a scroll view as its parent). What I am not sure is the best/recommendend way around this.
I tried adding the picker to the superView of the UIViewController's view but no dice:
[myViewController.view.superView addSubView:myPicker];
I still want to keep all the nice keyboard effects but would like my picker to behave like the keyboard, slide up and stay fixed in position and then slide away when done.
Any help would be greatly appreciated.
Dave
A: If you are using UITextView for the UIPicker you can try and use the "inputView" and iOS will manage animation and view hierarchy for you.
You can also always create a containing UIView that will contain the TableViewController's View property and add the UIPicker to him.
Good luck
A: One way to solve it is to create a subclass of UIActionSheet with a picker inside of it and display actionSheet when needed. At least it's what I did in similar situation.
| |
doc_23526284
|
structure(list(customer_id = c("A", "A", "A", "A", "A", "A",
"A", "A", "B", "B", "B", "B", "B"), state = c("NC", "NC", "NC",
"NC", "NC", "NC", "NC", "NC", "KA", "KA", "KA", "KA", "KA"),
value = c(20.4, 29, 26, 40, 35, 36, 28, 41, 70, 75, 78, 99,
40), Date = structure(c(17784, 17791, 17798, 17805, 17812,
17819, 17826, 17833, 17608, 17615, 17622, 17629, 17636), class = "Date")), row.names = c(NA,
-13L), class = "data.frame")
I have so many customers of data from different state with different start and end dates.
I'd like to convert this data to time_series data and perform exponential smoothing using hw method.
The code which I have tried to convert to time_series is:
temp <- multiple_ts %>%
group_by(state,customer_id) %>%
ts(multiple_ts$value, frequency = 52)
I used frequency as 52 because the data is weekly_data,but the code is throwing an error
Warning messages:
1: In data.matrix(data) : NAs introduced by coercion
2: In data.matrix(data) : NAs introduced by coercion
my output_data is
structure(c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 20.4, 29,
26, 40, 35, 36, 28, 41, 70, 75, 78, 99, 40, 17784, 17791, 17798,
17805, 17812, 17819, 17826, 17833, 17608, 17615, 17622, 17629,
17636), .Dim = c(13L, 4L), .Dimnames = list(NULL, c("customer_id",
"state", "value", "Date")), .Tsp = c(20.9384615384615, 21.1692307692308,
52), class = c("mts", "ts", "matrix"))
Can someone help me in R.
Thanks in Advance
| |
doc_23526285
|
My structure in disk is this one:
src
┣ css
┃ ┣ color.css.ts
┃ ┗ size.css.ts
┣ button.css.ts
┣ WCButton.ts
┗ WcTheme.ts
Let me explain:
*
*Css folder is to include separate files for declare defaults (in this example colors and size):
import { css } from "lit-element";
export const defaultColor = css`
.primary{
background: #356e3b;
}
.secondary{
background: #5b8e48;
}
.terciary{
background: #302e2b;
}
`;
(color.css.ts code)
*WcTheme.ts file is to integrate the files inside css folder into a single file:
import { defaultSize } from './css/size.css';
import { defaultColor } from './css/color.css';
import { LitElement } from 'lit-element';
export class WcTheme extends LitElement {
static styles = [defaultColor, defaultSize];
}
*button.css.ts are the CSS rules for a concrete component (in this case, for a button)
import { css } from "lit-element";
export const buttonStyles = css`
.btn-default {
border: 1px solid lime;
}
*WcButton.ts is the code definition of the web component (button)
import { LitElement, html } from 'lit-element';
import { WcTheme } from './WcTheme';
import { buttonStyles } from "./button.css";
export class WcButton extends LitElement {
static get styles() {
return [WcTheme.getStyles(),buttonStyles];
}
public render() {
return html`
<button
type="button"
class="btn-default"
>
<span class="primary h1">Test</span>
</button>
`;
}
}
This structure throw the next error:
[tsc] src/WCButton.ts(6,14): error TS2417: Class static side 'typeof WcButton' incorrectly extends base class static side 'typeof LitElement'.
[tsc] Types of property 'styles' are incompatible.
[tsc] Type '(CSSResult | CSSStyleSheet | CSSResultArray | undefined)[]' is not assignable to type 'CSSResult | CSSStyleSheet | CSSResultArray | undefined'.
[tsc] Type '(CSSResult | CSSStyleSheet | CSSResultArray | undefined)[]' is not assignable to type 'CSSResultArray'.
[tsc] The types returned by 'concat(...)' are incompatible between these types.
[tsc] Type '(CSSResult | CSSStyleSheet | CSSResultArray | undefined)[]' is not assignable to type '(CSSResult | CSSStyleSheet | CSSResultArray)[]'.
[tsc] Type 'CSSResult | CSSStyleSheet | CSSResultArray | undefined' is not assignable to type 'CSSResult | CSSStyleSheet | CSSResultArray'.
[tsc] Type 'undefined' is not assignable to type 'CSSResult | CSSStyleSheet | CSSResultArray'.
[tsc]
[tsc] 22:12:09 - Found 1 error. Watching for file changes.
because I can integrate CSSResultArray created by WcTheme.ts and CSSResult created in button.css.ts.
Could anyone help me to solve that or would be a better solution for do that?
Thanks in advance.
A: I have solved this with the same file structure, and in WcButton.ts I have changed:
static get styles() {
return [WcTheme.getStyles(), buttonStyles]; }
to
static get styles() {
return [...WcTheme.styles, buttonStyles]; }
| |
doc_23526286
|
import numpy as np
import argparse
import cv2
# initialize the current frame of the video, along with the list of
# ROI points along with whether or not this is input mode
frame = None
roiPts = []
inputMode = False
def selectROI(event, x, y, flags, param):
# grab the reference to the current frame, list of ROI
# points and whether or not it is ROI selection mode
global frame, roiPts, inputMode
# if we are in ROI selection mode, the mouse was clicked,
# and we do not already have four points, then update the
# list of ROI points with the (x, y) location of the click
# and draw the circle
if inputMode and event == cv2.EVENT_LBUTTONDOWN and len(roiPts) < 4:
roiPts.append((x, y))
cv2.circle(frame, (x, y), 4, (0, 255, 0), 2)
cv2.imshow("frame", frame)
def main():
# construct the argument parse and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-v", "--video",
help = "path to the (optional) video file")
args = vars(ap.parse_args())
# grab the reference to the current frame, list of ROI
# points and whether or not it is ROI selection mode
global frame, roiPts, inputMode
# if the video path was not supplied, grab the reference to the
# camera
if not args.get("video", False):
camera = cv2.VideoCapture(0)
# otherwise, load the video
else:
camera = cv2.VideoCapture(args["video"])
# setup the mouse callback
cv2.namedWindow("frame")
cv2.setMouseCallback("frame", selectROI)
# initialize the termination criteria for cam shift, indicating
# a maximum of ten iterations or movement by a least one pixel
# along with the bounding box of the ROI
termination = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 1)
roiBox = None
# keep looping over the frames
while True:
# grab the current frame
(grabbed, frame) = camera.read()
# check to see if we have reached the end of the
# video
if not grabbed:
break
# if the see if the ROI has been computed
if roiBox is not None:
# convert the current frame to the HSV color space
# and perform mean shift
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
backProj = cv2.calcBackProject([hsv], [0], roiHist, [0, 180], 1)
# apply cam shift to the back projection, convert the
# points to a bounding box, and then draw them
(r, roiBox) = cv2.CamShift(backProj, roiBox, termination)
pts = np.int0(cv2.cv.BoxPoints(r))
cv2.polylines(frame, [pts], True, (0, 255, 0), 2)
# show the frame and record if the user presses a key
cv2.imshow("frame", frame)
key = cv2.waitKey(1) & 0xFF
# handle if the 'i' key is pressed, then go into ROI
# selection mode
if key == ord("i") and len(roiPts) < 4:
# indicate that we are in input mode and clone the
# frame
inputMode = True
orig = frame.copy()
# keep looping until 4 reference ROI points have
# been selected; press any key to exit ROI selction
# mode once 4 points have been selected
while len(roiPts) < 4:
cv2.imshow("frame", frame)
cv2.waitKey(0)
# determine the top-left and bottom-right points
roiPts = np.array(roiPts)
s = roiPts.sum(axis = 1)
tl = roiPts[np.argmin(s)]
br = roiPts[np.argmax(s)]
# grab the ROI for the bounding box and convert it
# to the HSV color space
roi = orig[tl[1]:br[1], tl[0]:br[0]]
roi = cv2.cvtColor(roi, cv2.COLOR_BGR2HSV)
#roi = cv2.cvtColor(roi, cv2.COLOR_BGR2LAB)
# compute a HSV histogram for the ROI and store the
# bounding box
roiHist = cv2.calcHist([roi], [0], None, [16], [0, 180])
roiHist = cv2.normalize(roiHist, roiHist, 0, 255, cv2.NORM_MINMAX)
roiBox = (tl[0], tl[1], br[0], br[1])
# if the 'q' key is pressed, stop the loop
elif key == ord("q"):
break
# cleanup the camera and close any open windows
camera.release()
cv2.destroyAllWindows()
if __name__ == "__main__":
main()
when running this code i got error in the 114th line showing 'break is not inside the loop"...can anybody help me to solve this error.
A: because the whole if is outside the loop...
just simply put it in to the while loop (by selecting lines and pressing tab, or ctrl+] in idle)
| |
doc_23526287
|
If IsEmpty(Cells(8, M8 + 9).Value) And IsEmpty(Cells(12, M8 + 9).Value) Then
Sheets("Sheet3").Cells(8, M8 + 9).Value = info
Sheets("Sheet3").Cells(12, M8 + 9).Value = "--------------"
Sheets("Sheet3").Range(Cells(8, M8 + 9), Cells(12, M8 + 9)).Interior.Color = RColor
M8 = M8 + 1
Else
M8 = M8 + 1
End If
I was wondering if there is a way that when the first condition is not met and goes to the Else branch to add 1 to the M8 variable. When it adds 1 to M8 I want it to go back to the top and repeat the if statement with the new value of M8.
A: Don't use an If? This would loop until the condition specified is no longer true; but as Gary noted above it's possible to get into an endless loop, so I've added an additional criteria to break the loop if it goes on for 100 iterations
iTried = 0
While IsEmpty(Cells(8, M8 + 9).Value) And IsEmpty(Cells(12, M8 + 9).Value) = True And iTried <=100
Sheets("Sheet3").Cells(8, M8 + 9).Value = info
Sheets("Sheet3").Cells(12, M8 + 9).Value = "--------------"
Sheets("Sheet3").Range(Cells(8, M8 + 9), Cells(12, M8 + 9)).Interior.Color = RColor
M8 = M8 + 1
Wend
' Now check WHY the loop ended... if the cells are empty and the counter is >100 throw a msgbox
If IsEmpty(Cells(8, M8 + 9).Value) And IsEmpty(Cells(12, M8 + 9).Value) = True And iTried >100 Then
MsgBox "Too many tries; gave up!"
End If
A: You need to come at this from the other direction. If you need M8 to meet a specific condition, make sure the condition is met before you do anything else:
Dim aborted As Boolean
Do While Not (IsEmpty(Cells(8, M8 + 9).Value) And IsEmpty(Cells(12, M8 + 9).Value))
M8 = M8 + 1
If M8 > 100 Then 'Or whatever your "give up" condition is
aborted = True
Exit Do
End If
Loop
If Not aborted Then
Sheets("Sheet3").Cells(8, M8 + 9).Value = info
Sheets("Sheet3").Cells(12, M8 + 9).Value = "--------------"
Sheets("Sheet3").Range(Cells(8, M8 + 9), Cells(12, M8 + 9)).Interior.Color = RColor
End If
| |
doc_23526288
|
ex:
Output: 1 2 3 4 5 6 7 8 9 10
Input:1
Output:2 3 4 5 6 7 8 9 10
Input:5
Output:2 3 4 6 7 8 9 10
(only using while or do-while or for)->(not using array)
A: //let's say that the variable x contains the inputted number, 5 in this case
for (int i = 1; i <= 10; i++){
if (i != x)
printf("%d ", i);
}
The output will be:
1 2 3 4 6 7 8 9 10
A: #include <bitset>
#include <iostream>
...
constexpr int N = 10;
std::bitset<N+1> mask {-1ul};
while (true) {
int inp;
cin >> inp;
if (inp < 1 || inp > N)
continue;
mask.reset(inp);
for (int i = 1; i < N; ++i) {
if (mask.test(i)) {
std::cout << i << '\n';
}
}
}
A: I have tested this code on VS2017. I believe you will get an idea of how to do it. Of course, you can improve the efficiency of the source code.
#include "stdafx.h"
#include <iostream>
#include <bitset>
using namespace std;
int main()
{
constexpr int iBitNum = 10;
std::bitset<iBitNum + 1> mask;
mask.set();
int _size = mask.count();
for (int i = 0; i < _size; ++i)
{
mask[i] = 0;
}
int inp = 0;
int b = 0;
while (true)
{
cout << "Enter the number which you do not want to display" << endl;
cin >> inp;
cout << "Here is the result" << endl;
for (size_t i = 0; i < iBitNum; i++)
{
if (i+1==inp)
{
continue;
}
b = mask[i] | i+1;
cout << b << " ";
}
cout << endl;
}
return 0;
}
| |
doc_23526289
|
I believe the issue is the "connect" function in the player_socket.ex. ( I have a player resource ). Here is the function:
def connect(%{"token" => token}, socket) do
case Phoenix.Token.verify(socket, "player auth", token, max_age: @max_age) do
{:ok, player_id} ->
player = Repo.get!(Player, player_id)
{:ok, assign(socket, :current_player, player)}
{:error, _reason} ->
:error
end
end
I'm signing the token in a meta tag in app.html.eex. <%= tag :meta, name: "channel_token", content: Phoenix.Token.sign(@conn, "player auth", :player_id) %>
Then in the lobby_channel.ex I'm trying to join the channel:
def join("lobby:lobby", _params, socket) do
send(self(), :after_join)
{:ok, assign(socket, :player_id, :current_player)}
end
def handle_info(:after_join, socket) do
push socket, "presence_state", Presence.list(socket)
{:ok, _} = Presence.track(socket, socket.assigns.current_player, %{
online_at: inspect(System.system_time(:seconds))
})
{:noreply, socket}
end
I read the docs but can't seem to figure out why I'm unable to connect to the websocket with the "current_player" so that I can use Presence to display who is online and the player's names to associate with their chat messages. Any insight is greatly appreciated! I have the repo here:
https://github.com/EssenceOfChaos/gofish
UPDATE
I am using a "current_player" plug to store the player struct in the conn as "current_player.
%Plug.Conn{adapter: {Plug.Adapters.Cowboy.Conn, :...},
assigns: %{current_player: %Gofish.Accounts.Player{__meta__: #Ecto.Schema.Metadata<:loaded, "players">,
email: "example@aol.com", id: 6,
Here is my updated lobby_channel.ex:
def join("lobby:lobby", _params, socket) do
send(self(), :after_join)
{:ok, socket}
end
def handle_info(:after_join, socket) do
push socket, "presence_state", Presence.list(socket)
{:ok, _} = Presence.track(socket, socket.assigns.current_player.id, %{
username: socket.assigns.current_player.username,
online_at: inspect(System.system_time(:seconds))
})
{:noreply, socket}
end
A: Your player_socket.ex is fine. You do have a few issues though:
In your layout/app.eex template:
Phoenix.Token.sign(@conn, "player auth", :player_id) is literally writing an atom :player_id instead of the ID of the player. In order to write the ID of the player, you should use @player_id and add a plug that assigns the value globally to your router.ex like so:
pipeline :browser do
[...]
plug :fetch_current_user
end
...
def fetch_current_user(conn, _) do
assigns(conn, :current_player, get_session(conn, :current_player)
end
This will make @current_player available in all your templates, which you can then use in app.eex:
<%= tag :meta, name: "channel_token", content: Phoenix.Token.sign(@conn, "player auth", @current_player) %>
(you should write this conditionally if @current_player isn't nil and stop your JS client from attempting websocket connections if it is, btw)
This change will immediately fix your inability to connect to the websocket as long as you've signed in, but you still have one more issue:
{:ok, assign(socket, :player_id, :current_player)} in your loby_channel.ex is assigning the atom :current_player literally instead of using the actual value of the current player's ID, but you don't need this line at all. Instead, in your :after_join, you should do
{:ok, _} = Presence.track(socket, socket.assigns.current_player.username, %{
online_at: inspect(System.system_time(:seconds))
})
Notice I changed socket.assigns.current_player to socket.assigns.current_player.username. This is because you cannot assign a struct as a Presence key.
Alternatively you could do
{:ok, _} = Presence.track(socket, socket.assigns.current_player.id, %{
username: socket.assigns.current_player.username,
online_at: inspect(System.system_time(:seconds))
})
and in your socket.js you'd use first.username instead of id inside renderOnlineUsers
| |
doc_23526290
|
I had assumed that these operations would be equivalent, but they are clearly not. Could someone please help me understand why this doesn't work? (if it helps, I am just typing this test case in the console of Chrome 87).
> test_data = Uint8Array.from([1,2,3,4])
Uint8Array(4) [1, 2, 3, 4]
> view = new DataView(test_data.buffer)
DataView(4) {}
> Uint8Array.from(view.buffer) // this doesn't work for some reason ?
Uint8Array []
> new Uint8Array(view.buffer)
Uint8Array(4) [1, 2, 3, 4]
| |
doc_23526291
|
var clientCred = new ClientCredential("<client id>", "<secret>");
var authContext = new AuthenticationContext("https://login.windows.net/" + "<b2c tenant>");
var authResult = authContext.AcquireTokenAsync("https://graph.microsoft.com/", clientCred).Result;
var client = new GraphServiceClient(
new DelegateAuthenticationProvider(
async (requestMessage) =>
{
var token = authResult.AccessToken;
var result = await Task.FromResult(token);
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", token);
}));
var users = client
.Users
.Request()
.Select("memberOf") // not working
//.Select(u => new { u.MemberOf }) // not working
.Expand("memberOf") // not working
//.Expand(u => new { u.MemberOf }) // not working
.GetAsync()
.Result
.ToList();
As a result I get list of my users with some data but the MemberOf field is always null (though i'm 100% sure they have at least one assigned group). Yet, this works as expected:
var u = client.Users["<id>"].MemberOf.Request().GetAsync().Result;
Just to be sure, I've granted my app full app permissions, nothing changed. Am I missing something?
A: It's my first answer I hope I can help you.
You should use the beta version since v1.0 does not implement the "memberOf" expand, to change the sdk to the beta version you have to add:
client.BaseUrl = "https://graph.microsoft.com/beta";
I usually include the expand using QueryOption as follows:
List<QueryOption> options = new List<QueryOption> { new QueryOption("$Expand", "MemberOf") };
But I think that the way you are using it will not have any problems
Try this code:
var clientCred = new ClientCredential("<client id>", "<secret>");
var authContext = new AuthenticationContext("https://login.windows.net/" + "<b2c tenant>");
var authResult = authContext.AcquireTokenAsync("https://graph.microsoft.com/", clientCred).Result;
var client = new GraphServiceClient(
new DelegateAuthenticationProvider(
async (requestMessage) =>
{
var token = authResult.AccessToken;
var result = await Task.FromResult(token);
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", token);
}));
//Change to the beta version
client.BaseUrl = "https://graph.microsoft.com/beta";
//Parameters of the query
List<QueryOption> options = new List<QueryOption> { new QueryOption("$Expand", "MemberOf") };
// query with parameters
var users = await graphClient.Users.Request(options).GetAsync();
| |
doc_23526292
|
But I am getting below error at transformer.transform(input, output) in my java transformation class.
Please help me in this.
Stack Trace:
java.io.IOException: Stream Closed
net.sf.saxon.trans.XPathException: java.io.IOException: Stream Closed
at net.sf.saxon.event.XMLEmitter.close(XMLEmitter.java:264)
at net.sf.saxon.event.ProxyReceiver.close(ProxyReceiver.java:90)
at net.sf.saxon.event.UncommittedSerializer.close(UncommittedSerializer.java:53)
at net.sf.saxon.event.ImplicitResultChecker.close(ImplicitResultChecker.java:92)
at net.sf.saxon.event.ProxyReceiver.close(ProxyReceiver.java:90)
at net.sf.saxon.event.ComplexContentOutputter.close(ComplexContentOutputter.java:507)
at net.sf.saxon.Controller.transformDocument(Controller.java:1848)
at net.sf.saxon.Controller.transform(Controller.java:1621)
Java code snippet:
String outputDirectory = fileParentLocation + "\\resultFolder\\";
FileTools.createDirectory(new File(outputDirectory));
try {
TransformerFactory factory =
TransformerFactory.newInstance("net.sf.saxon.TransformerFactoryImpl", getClass().getClassLoader());
InputStream xsltResourceAsStream =
getClass().getClassLoader().getResourceAsStream("ConvertInputXmlFiles.xslt");
Source xslt = new StreamSource(xsltResourceAsStream);
Result output = new StreamResult(new File(outputDirectory + "test.xml"));
Transformer transformer = factory.newTransformer(xslt);
transformer.setParameter("versionName", versionName);
if (filesToBeTransformed != null && !filesToBeTransformed.isEmpty()) {
for (File file : filesToBeTransformed) {
Source input = new StreamSource(file);
transformer.transform(input, output);
}
}
}
Thanks in advance !!
A: You're trying to append multiple transformation results to the same output stream, and that doesn't work.
I think it would probably work if you created a FileOutputStream and supplied that in the StreamResult, instead of supplying the File. Basically, whoever creates a stream is responsible for closing it, and if you supply a File, then Saxon creates the stream, and will close it at the end of the transformation, but if you create the stream, then you can choose whether to close it or not.
Your prose question says you're trying to produce multiple output documents, but your code seems to be trying to produce a single result document. Which is it?
Note also, with Saxon we recommend doing TransformerFactory.newTemplates() once to compile the stylesheet, and then creating a new Transformer for each transformation using Templates.newTransformer(). Serial reuse of a single Transformer is allowed, but may cause unnecessary accumulation of resources in internal caches.
| |
doc_23526293
|
If not, are there plans for Windows 7 extensions for Python?
A: pywin32 extensions works fine on Windows 7.
| |
doc_23526294
|
var fieldsToSet = {
somename: req.body.username,
email: req.body.email.toLowerCase(),
$addToSet:{array_field:'some single value'},
search: [
req.body.username,
req.body.email,
],
};
I update it using
req.app.db.models.User.findByIdAndUpdate(req.user.id, fieldsToSet, options, function(err, user) {
if (err) {
return workflow.emit('exception', err);
}
workflow.emit('patchAdmin', user);
});
However it does not seem to work. COuld someone please help me out?
var userSchema = new mongoose.Schema({
username: { type: String, unique: true },
password: String,
array_field:[String],
email: { type: String, unique: true },
A: You cannot mix what are essentially two types of "update" options. MongoDB will either "replace" the whole document with the arguments provided or apply the "operators" you specify.
It appears that you want $set here as well:
var fieldsToSet = {
"$set": {
"somename": req.body.username,
"email": req.body.email.toLowerCase(),
"search": [
req.body.username,
req.body.email,
]
},
"$addToSet":{ "array_field": 'some single value' },
};
| |
doc_23526295
|
<h:form>
<p:commandButton type="submit" value="Add" ajax="true" update=":tabs"
actionListener="#{sideBar.setCurrentFaceltName('todolist')}">
</p:commandButton>
</h:form>
and this is the layout where the facet is included
<p:layoutUnit id="tabs" style=" position: relative;" position="center">
<ui:include src="/WEB-INF/facelts/#{sideBar.currentFaceltName}.xhtml" />
</p:layoutUnit>
and i build the facet programmatically using binding
<h:body>
<h:panelGroup binding="#{test.dynamicFormGroup}" />
</h:body>
just a child UI component for the panel for test and it works fine if i include the facet directly like this
<ui:include src="/WEB-INF/facelts/todolist.xhtml" />
can any one help me with this?
thanks in advance
| |
doc_23526296
|
"records": [
{
"record_id": "REC000000000000009",
"name": "test 1",
"email": "test@test.com"
},
{
"record_id": "REC00000000000000A",
"name": "test race #2",
"email": "test@test.com"
}
]
When I run it through the following logic only the "record_id" key has quotes. Also, only the "record_id" value does not have quotes.
NSData *httpData = [results dataUsingEncoding:NSUTF8StringEncoding];
NSError* error;
NSDictionary *dict = [NSJSONSerialization
JSONObjectWithData:httpData
options:0
error:&error];
The result:
records: (
{
email = "test@test.com";
name = "test 1";
"record_id" = REC000000000000009;
},
{
email = "test@test.com";
name = "test race #2";
"record_id" = REC00000000000000A;
}
)
Any help understanding why this is happening is appreciated.
A: This just happens to be how - [NSDictionary description] formats the dictionary keys (and values). (In particular, this is the legacy NextStep property list format.) This format doesn't demand that strings without punctuation be quoted.
(Of course, neither the keys or values have actual quotes in them.)
| |
doc_23526297
|
e.g.
self.getStepsBetweenDates(NSDate(timeIntervalSince1970: 1543392126) as Date, date2: NSDate(timeIntervalSince1970: 1543393044) as Date) returns (Int) 1488
self.getStepsBetweenDates(NSDate(timeIntervalSince1970: 1543392126) as Date, date2: NSDate(timeIntervalSince1970: 1543393045) as Date) returns (Int) 0
self.getStepsBetweenDates(NSDate(timeIntervalSince1970: 1543392126) as Date, date2: NSDate(timeIntervalSince1970: 1543393046) as Date) returns (Int) 1488
getStepsBetweenDates method looks like this
func getStepsBetweenDates(_ date1: Date, date2: Date) -> Int{
let group = DispatchGroup()
group.enter()
var steps = 0
self.pedometer.queryPedometerData(from: date1, to: date2, withHandler: {
pData, error in
if let e = error{
print("Error querying pedometer", e.localizedDescription)
}else{
if let data = pData{
steps = Int(data.numberOfSteps)
}
group.leave()
}
})
_ = group.wait(timeout: DispatchTime.distantFuture)
return steps
}
A: queryPedometerData is an asynchronous call
Ordinarily you would not want to return the steps in the getStepsBetweenDates call because it is asynchronous.
If you changed the var steps = 0 to var steps = [some random int] then it's likely you'll get that number back instead of 0 because of the race condition set up.
More ideally would be to implement your code as a closure/callback or another form of asynchronous handling.
eg:
self.pedometer.queryPedometerData(from: date1, to: date2) { (data, error) in
// Do something here with data.numberOfSteps
}
Here's an article on Medium about async code:
https://medium.com/ios-os-x-development/managing-async-code-in-swift-d7be44cae89f
| |
doc_23526298
|
If any image gets bigger I use the following code to get a new width.
This is my uploader file.
def store_dimensions
if file && model
width, height = ::MiniMagick::Image.open(file.file)[:dimensions]
if width>700
return 700
else
return width
end
end
Then I created a version named best_fit
process :store_dimensions
version :best_fit do
process :resize_to_fill => [store_dimensions,200]
end
It can't find the store_dimensions method. On the other hand, if I use self keyword while declaring store_dimensions method, then it works, but then the "file" identifier is become an unknown entity.
How can I get the value of the uploaded image and according to that I can create a new version of it.
A: The following code saved my ass today. I'm happy that I solved it.
def store_dimensions
if file && model
width, height = ::MiniMagick::Image.open(file.file)[:dimensions]
if width>700
Rails.logger.info "#{width}"
finalHeight=((700*height)/width)
self.class.version :best_fit do
process :resize_to_fill => [700,finalHeight]
end
else
Rails.logger.info "#{width}"
self.class.version :best_fit do
process :resize_to_fill => [width,height]
end
end
end
end
#run the store_dimensions methods
process :store_dimensions
A: For any lost wanderers, this is what you're looking for:
class Uploader
version :my_version do
process :my_processor
end
def my_processor
# model is available here!
manipulate! do |img|
img.combine_options do |cmd|
cmd.resize [model.width, model.height].join('x')
end
img
end
end
end
Example of custom process method
| |
doc_23526299
|
private static Map<Integer, EmptyTile> createAllPossibleEmpyTiles() {
Map<Integer,EmptyTile> emptyTileMap = new HashMap<Integer, EmptyTile>();
for (int i = 0; i <64 ; i++) {
emptyTileMap.put(i,new EmptyTile(i));
}
return emptyTileMap;
}
?
A: So, let's examine the traditional way and try to convert it into the stream format.
Map<Integer, EmptyTile> emptyTileMap = new HashMap<>();
for (int i = 0; i < 64; i++) {
emptyTileMap.put(i, new EmptyTile(i));
}
return emptyTileMap;
There's a couple of things going on here.
*
*We explicitly loop through the interval of [0, 64)
*We generate tile objects based on the values of the interval
*We maintain a map to keep all the generated tile objects
So, we can start the conversion from the very first part - the explicit loop. This can be achieved using
IntStream.range(start, end) function.
Next up, we will generate the tile objects based on the interval values, so:
IntStream.range(0, 64)
.mapToObj(number -> new EmptyTile(number))
We can use method reference here to shorten the code:
IntStream.range(0, 64)
.mapToObj(EmptyTile::new)
Next, we need to add those values to the map. To do this, we need toMap collector. It accepts
a key mapper and a value mapper (it has 2 more forms). Our key will be the generated number,
and the value is the object itself, so, this is the final look.
private Map<Integer, EmptyTile> createAllPossibleEmptyTilesStream() {
return IntStream.range(0, 64)
.mapToObj(EmptyTile::new)
.collect(toMap(EmptyTile::getValue, x -> x));
}
Here, x -> x is the identity function. The value mapper is a function which accepts an EmptyTile
object and returns something else. Since we need the value to be object itself, we just return it.
A: one possibility to do this:
Map<Integer, EmptyTile> emptyTileMap = IntStream.range(0, 64).boxed().collect(toMap(i -> i, EmptyTile::new));
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.