2020-12-31

Insert failed: 1064 (42000): You have an error in your SQL syntax;

import mysql.connector from mysql.connector import Error as MySQLError

class DatabaseManager(): """ This class manages access and CRUD operations to a MySQL database """

def __init__(self, host, port, name, user, password):
    """The constructor

    Args:
        host (str): server host of the database
        port (int): server port of the database
        name (str): name of the database
        user (str): name of user
        password (str): password of user
    """
    self.host = host
    self.port = port
    self.name = name
    self.user = user
    self.password = password
    self.__connection = None
    try:
        print(
            print(
                f"\n-->>> Connecting to MySQL Database: {user}@{host}:{port} <<<---\n")
        )
        connection = mysql.connector.connect(
            host=host, port=port, user=user, passwd=password, db=name)

        self.__connection = connection
        print(f'\n-->>> MySQL Database connected successfully<<---\n')

    except MySQLError as err:
        print(f"\n-->>> MySQL Database connected failed: {err} <<---\n")

def create_job_listings_table(self): """ create job listings table """

try:
    with self.__connection.cursor() as cursor:
        # create table
        sql = """CREATE TABLE IF NOT EXISTS `job_listings` (
            `id` INT NOT NULL AUTO_INCREMENT,
            `title` VARCHAR(255) NOT NULL,
            `link` TEXT,
            `employer` VARCHAR(255),
            `logo` TEXT,
            `location` VARCHAR(255),
            `type` VARCHAR(255),
            `salary` VARCHAR(255),
            `summary` TEXT,
            `sector` VARCHAR(255),
            `timestamp` VARCHAR(255),
            PRIMARY KEY (`id`)
        ) DEFAULT CHARSET=utf8 COLLATE=utf8_bin AUTO_INCREMENT=1;
        """
        cursor.execute(sql)
    print(f"\n-->>> Table created successfully <<---\n")
except MySQLError as err:
    print(f"\n-->>> Table creation failed: {err} <<---\n")

def add_job_listings_to_table(self, job_listings): """bulk insert job listings to table

Args:
    job_listings (list): list of job listings
"""
try:
    values = ""
    for job_listing in job_listings:
        value = f"({job_listing.title}, {job_listing.link}, {job_listing.employer}, 
        {job_listing.logo}, {job_listing.location}, {job_listing.type}, {job_listing.salary}, 
        {job_listing.summary}, {job_listing.sector}, {job_listing.timestamp}), "
        values += value

    print(f"-->>> Inserting records... <<---\n")

    with self.__connection.cursor() as cursor:
        # bulk insert job listings
        sql = """INSERT INTO `job_listings` 
        (`id`,`title`, `link`, `employer`, `logo`, `location`, `type`, `salary`, `summary`, 
        `sector`, `timestamp`) 
        VALUES {values};
        """.format(values=values)
        cursor.execute(sql)
    print(f"\n-->>> Records inserted successfully <<---\n")

except MySQLError as err:
    print(f"\n-->>> Insert failed: {err} <<---\n")

def drop_job_listings_table(self): """ drop job listings table from the database """ try: print(f"-->>> Dropping table... <<---\n") with self.__connection.cursor() as cursor: # drop table sql = """DROP TABLE IF EXISTS job_listings; """ cursor.execute(sql) print(f"\n-->>> Table dropped successfully <<---\n") except MySQLError as err: print(f"\n-->>> Failed to drop table: {err} <<---\n")



from Recent Questions - Stack Overflow https://ift.tt/3rKbdXM
https://ift.tt/eA8V8J

Cannot POST /updatedata

1.I am trying to modify my data in mysql database but getting error

  1. I am able to add the data but unable to modify the data.

  2. I have created a seperate tab in main page as modify. What changes needs to be done?


**var mysql = require('mysql');
var express = require('express');
var bodyParser = require('body-parser');
var connection = mysql.createConnection({
    host     : 'localhost',
    user     : 'root',
    password : '',
    database : 'mr',
    port: '3308',
});
var app = express();
app.use(bodyParser.urlencoded({extended : false}));
app.use(bodyParser.json());
app.get('/', function(request,response){
    response.sendFile(__dirname + '/home.html');
});
app.get('/update', function(request, response){
    response.sendFile(__dirname + '/modify.html');
});
app.put('/updatedata',function(req,res){
    
    connection.query('update hp set Name=?,Address=?,Country=?,Phone=? where Id=?',[req.body.Name,req.body.Address,req.body.Country,req.body.Phone,req.body.Id],function(error,results,fields){
        if(err) throw err;
        console.log("Record updated");
        res.redirect('/home');
    });
});
app.get('/home', function(request, response) {
    
    response.sendFile(__dirname + '/home.html');
});
app.listen(5000);
console.log('Server Started');**


from Recent Questions - Stack Overflow https://ift.tt/3rJPqPF
https://ift.tt/eA8V8J

Java. Formatting array

My problem is this: i have 2d array which is filled with numbers. I have to output it in a way that it shows "*" between neighbours with different values and with " " if values are different. Example:

   *********
   *1 1*3*4*
   ***** * *
   *2 2*3*4*
   *********

I have tried many things like creating another array with [Nx2][Mx2] size or System.out.format but it in the end its never formatte the way I like. Any suggestions how can I solve this?



from Recent Questions - Stack Overflow https://ift.tt/380qo70
https://ift.tt/eA8V8J

How to make an icon slideshow with jQuery

Hi I am building a small slideshow of icons and also want to have data inside the icons like its speed and color. I've loaded jQuery from the top of my page.

<body>
<div class="main-container">
    <div class="object-container">

    <div class="icon-container">
        <i class="fa fa-car" id="active"></i>
        <i class="fa fa-bicycle" id="not-active"></i>
        <i class="fa fa-plane" id="not-active"></i>
        <i class="fa fa-ship" id="not-active"></i>
        <i class="fa fa-fighter-jet" id="not-active"></i>
        <i class="fa fa-space-shuttle" id="not-active"></i>
    </div>
    <div class="arrow-buttons">
        <a href="" class="right-arrow"></a>
        <a href="" class="left-arrow"></a>
    </div>
    </div>
</div>
Here is the jquery to press the right arrow button to change slide across the icons but it doesnt seem to be working?
$(document).ready(function(){
$('.right-arrow').on('click', function(){
    let currentImg = $('#active');
    let nextImg = currentImg.next();

    if(currentImg.length){
        currentImg.removeAttr('#active').css('z-inex', -10)
        nextImg.attr('#active').css('z-index', 10);
    }
})

})



from Recent Questions - Stack Overflow https://ift.tt/37YPbIE
https://ift.tt/eA8V8J

Error Message in Dsharp with String Prefix

 var commandsConfig = new CommandsNextConfiguration
        {
            **StringPrefix = new string[] { configJson.Prefix },** //here is the error
            EnableDms = false,
            EnableMentionPrefix = true,

                
        };

So, I got an error which is saying "Cannot implicitly convert type 'string[]' to 'string' ". Can I ask why my code does not work? I am learning Dsharp by an online course and the man who made the course has no problem with this... Please help me!



from Recent Questions - Stack Overflow https://ift.tt/2WZyo26
https://ift.tt/eA8V8J

Why do my TableView cells need reuse identifiers?

To practice my programming and keep track of my progress I'm building an app for myself. I've created a tableview and for each section and independent cells for each requirement. Now Xcode is upset because each prototype cell doesn't have an identifier.

I've looked at the Swift docs and gone through Youtube vids on the topic but I still don't understand what reuse identifiers are or what they are used for, let alone how it would help in my case.

Screenshot



from Recent Questions - Stack Overflow https://ift.tt/34UQKFE
https://ift.tt/38LLkxS

Copy a Map Object in Java

Tried to follow the same way as in <How do I copy an object in Java?>.

But it does not work with Map object in the following codes. I want to copy the original map data to currMap. The current outputs are -

0 1 2 3 null null null

I want it to be - 0 1 2 3 0 2 3

What are missing here?

Thanks

import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Queue;

class mapCopy{
    private Map<Character, Queue<Integer>> map;
    mapCopy(Map<Character, Queue<Integer>> map){
        this.map=map;
    }
    
    mapCopy(mapCopy mapcopy){
        this.map=mapcopy.map;
    }
    
    Map<Character, Queue<Integer>> getMap(){
        return this.map;
    }
}

public class Test {

    static Map<Character, Queue<Integer>> BuildMap(){
        String toMatch="able";
        Map<Character, Queue<Integer>> map = new HashMap<>();
        
        int i=0;
        for(var c:toMatch.toCharArray()) {
            Queue<Integer> q = map.get(c);
            if(q==null)
                q=new ArrayDeque<Integer>();
            
            q.add(i);
            map.put(c, q);          
            i++;
        }
        
        return map;
    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Map<Character, Queue<Integer>> map = BuildMap();
        
        List<String> dic = Arrays.asList("able", "ale");        
                        
        for(var d:dic) {
            var copy1 = new mapCopy(map);
            var copy2 = new mapCopy(copy1);
            
            var currMap = copy2.getMap();
            
            for(var c:d.toCharArray()) {        
                    System.out.println(currMap.get(c).poll());
            }
        }
    }

}


from Recent Questions - Stack Overflow https://ift.tt/2Md23m2
https://ift.tt/eA8V8J

I need help, homework

Hello I was working on a new robot and it say error await fart() can someone tell me what is wrong? I try to replase text with js input.

jest tekstem stosowanym jako przykładowy wypełniacz w przemyśle poligraficznym. Został po raz pierwszy użyty w XV w. przez nieznanego drukarza do wypełnienia tekstem próbnej książki. Pięć wieków później zaczął być używany przemyśle elektronicznym,

let isFarted = false;
let input = "hello  my name is josh i am from united kingdom";
async function ILoveSmeell() {
    while (isFarted) {
    }
}

async function goStink() {
    isFarted = true;
    console.log("fixing");
    await sleep(100); // sleep for bit
    input = input.replace("united kingdom", "AMERICA"); // ?
    isFarted = false;
}

async function fart_do() {
    if (isFarted) {
        await ILoveSmeell();
        console.log("fixed 2")
    } else {
        await goStink();
        console.log("löl")
    }
}

(async () => {
    fart();
    await fart();
    console.log("lol");
})();


from Recent Questions - Stack Overflow https://ift.tt/3rIs5Ok
https://ift.tt/eA8V8J

SqsAckSink makes the Akka stream hanging forever causing graph restarts

I'm trying to implement a simple workflow with an SQS source and a test with Localstack. And I cannot make it work if I add SqsAckSink, neither it works with SqsAckFlow. But if I remove SqsAckSink and just use Sink.seq(), then the test passes. Having the SqsAckSink or SqsAckFlow makes the test hanging forever. I have also enabled debug in the test and see that the same error repeats again and again making the graph restarting, but it doesn't make much sense to me. I'm posting the error messages below after the code snippets.

The code is:

    public class DefaultWorkflow implements Workflow {

  private Function<Throwable, Supervision.Directive> errorStrategy;
  private final ActorSystem actorSystem;
  private FlowMonitor<ProvisioningResult> workflowMonitor;
  private final String queueUrl;
  private final SqsAsyncClient asyncClient;

  @Inject
  public DefaultWorkflow(ActorSystem actorSystem, String queueUrl) {

    this.errorStrategy = exc -> (Supervision.Directive) Supervision.resume();
    this.actorSystem = actorSystem;
    this.queueUrl = queueUrl;

    asyncClient =
        SqsAsyncClient.builder()
            .region(Region.of(Localstack.getDefaultRegion()))
            .httpClient(AkkaHttpClient.builder().withActorSystem(actorSystem).build())
            .endpointOverride(new URI(queueUrl))
            .build();
    doWork();
  }

  private Flow<Message, ProvisioningResult, NotUsed> buildFlow() {
    return Flow.of(Message.class)
        .via(Flow.of(Message.class).map(m -> ProvisioningResult.builder().body(m.body()).build()));
  }

  @Override
  public Source<ProvisioningResult, FlowMonitor<ProvisioningResult>> getSource() {
    Source<Message, NotUsed> sqsSource =
        RestartSource.onFailuresWithBackoff(
            Duration.ofSeconds(1), Duration.ofSeconds(2), 0.1, this::createSQSSource);
    return sqsSource
        .via(buildFlow())
        .withAttributes(ActorAttributes.withSupervisionStrategy(errorStrategy))
        .monitorMat(Keep.right());
  }

  private Source<Message, NotUsed> createSQSSource() {
    SqsSourceSettings sqsSourceSettings = SqsSourceSettings.create().withMaxBatchSize(1);
    return SqsSource.create(queueUrl, sqsSourceSettings, asyncClient);
  }

  @Override
  public FlowMonitor<ProvisioningResult> getWorkflowMonitor() {
    return this.workflowMonitor;
  }

  private void doWork() {
    Pair<FlowMonitor<ProvisioningResult>, CompletionStage<Done>> run =
        getSource()
            .toMat(SqsAckSink.create(queueUrl, SqsAckSettings.create(), asyncClient), Keep.both())
            .run(actorSystem);
    workflowMonitor = run.first();
  }
}

The test looks like this:

  @Test
  public void getSource_givenMessage_shouldProduceResult()
      throws InterruptedException, ExecutionException, TimeoutException, URISyntaxException {
    String sqsName = "sqs2";
    String messageBody = "someMessage";
    String sqsUrl = initSQS(sqsName);
    generateSourceData(sqsUrl, messageBody);

    this.defaultWorkflow = new DefaultWorkflow(this.actorSystem, sqsUrl);

    Source<ProvisioningResult, FlowMonitor<ProvisioningResult>> source =
        defaultWorkflow.getSource();
    final CompletionStage<List<ProvisioningResult>> future =
        source.take(1).runWith(Sink.seq(), materializer);
    final List<ProvisioningResult> result = future.toCompletableFuture().join();
    assertEquals(1, result.size());
    assertEquals(result.get(0).getBody(), messageBody);
  }

  public void generateSourceData(String queueUrl, String messageBody) {
    client
        .sendMessage(
            SendMessageRequest.builder().queueUrl(queueUrl).messageBody(messageBody).build())
        .join();
  }

  private void initClient() throws URISyntaxException {
    System.setProperty(SdkSystemSetting.CBOR_ENABLED.property(), "false");
    AwsCredentials credentials = AwsBasicCredentials.create("somekey", "somevalue");
    StaticCredentialsProvider provider = StaticCredentialsProvider.create(credentials);

    client =
        SqsAsyncClient.builder()
            .region(Region.of(Localstack.getDefaultRegion()))
            .httpClient(AkkaHttpClient.builder().withActorSystem(ActorSystem.create()).build())
            .credentialsProvider(provider)
            .endpointOverride(new URI(Localstack.INSTANCE.getEndpointSQS()))
            .build();
  }

  protected String initSQS(String queueName) throws URISyntaxException {
    initClient();
    client
        .createQueue(CreateQueueRequest.builder().queueName(queueName).build())
        .join()
        .queueUrl();
    GetQueueUrlResponse response = client.getQueueUrl(GetQueueUrlRequest.builder().queueName(queueName).build()).join();
    System.out.println("Using queue " + response);
    log.info("Using queue {}", response);
    return response.queueUrl();
  }

When I enable debug, I see this error that repeats forever:

[info] [debug] s.a.a.c.i.ExecutionInterceptorChain - Creating an interceptor chain that will apply interceptors in the following order: [software.amazon.awssdk.awscore.interceptor.HelpfulUnknownHostExceptionInterceptor@41a58812, software.amazon.awssdk.services.sqs.internal.MessageMD5ChecksumInterceptor@4f626e56, software.amazon.awssdk.protocols.query.interceptor.QueryParametersToBodyInterceptor@4b5de362] [info] [debug] s.a.a.c.i.ExecutionInterceptorChain - Interceptor 'software.amazon.awssdk.protocols.query.interceptor.QueryParametersToBodyInterceptor@4b5de362' modified the message with its modifyHttpRequest method. [info] [debug] s.a.a.request - Sending Request: DefaultSdkHttpFullRequest(httpMethod=POST, protocol=http, host=localhost, port=4566, encodedPath=, headers=[amz-sdk-invocation-id, Content-Length, Content-Type, User-Agent], queryParameters=[]) [info] [debug] s.a.a.a.s.Aws4Signer - AWS4 String to sign: AWS4-HMAC-SHA256 [info] 20201230T233655Z [info] 20201230/us-east-1/sqs/aws4_request [info] 5e95b0e67072e57434cb0da9516ef2ef4c747760bda87e9207161f9834d6dc01 [info] [debug] s.a.a.request - Received error response: 500 [info] [debug] s.a.a.request - Retryable error detected. Will retry in 47ms. Request attempt number 2 [info] [debug] s.a.a.request - Retrying Request: DefaultSdkHttpFullRequest(httpMethod=POST, protocol=http, host=localhost, port=4566, encodedPath=, headers=[amz-sdk-invocation-id, Content-Length, Content-Type, User-Agent], queryParameters=[]) [info] [debug] s.a.a.a.s.Aws4Signer - AWS4 String to sign: AWS4-HMAC-SHA256 [info] 20201230T233655Z [info] 20201230/us-east-1/sqs/aws4_request [info] ebce46865d8fface363b83481672fa6a3b7a11f584f2ea7c1e2b56e381e33afc [info] [debug] s.a.a.request - Received error response: 500 [info] [debug] s.a.a.request - Retryable error detected. Will retry in 51ms. Request attempt number 3 [info] [debug] s.a.a.request - Retrying Request: DefaultSdkHttpFullRequest(httpMethod=POST, protocol=http, host=localhost, port=4566, encodedPath=, headers=[amz-sdk-invocation-id, Content-Length, Content-Type, User-Agent], queryParameters=[]) [info] [debug] s.a.a.a.s.Aws4Signer - AWS4 String to sign: AWS4-HMAC-SHA256 [info] 20201230T233655Z [info] 20201230/us-east-1/sqs/aws4_request [info] 4085d30b4fa9cce89c435ed7a6404539a665bc2bfd4322fafd4095d2cb58fab1 [info] [debug] s.a.a.request - Received error response: 500 [info] [debug] s.a.a.request - Retryable error detected. Will retry in 230ms. Request attempt number 4 [info] [debug] s.a.a.request - Retrying Request: DefaultSdkHttpFullRequest(httpMethod=POST, protocol=http, host=localhost, port=4566, encodedPath=, headers=[amz-sdk-invocation-id, Content-Length, Content-Type, User-Agent], queryParameters=[]) [info] [debug] s.a.a.a.s.Aws4Signer - AWS4 String to sign: AWS4-HMAC-SHA256 [info] 20201230T233655Z [info] 20201230/us-east-1/sqs/aws4_request [info] 618037af1ce6008ce721fd3ca9cddde2e3f2893d50bd9ff5a241cc2061e1d67f [info] [debug] s.a.a.request - Received error response: 500 [info] [warn] a.s.s.RestartWithBackoffSource - Restarting graph due to failure. stack_trace: [info] java.util.concurrent.CompletionException: software.amazon.awssdk.services.sqs.model.SqsException: null (Service: Sqs, Status Code: 500, Request ID: null) [info] at software.amazon.awssdk.utils.CompletableFutureUtils.errorAsCompletionException(CompletableFutureUtils.java:60) [info] at software.amazon.awssdk.core.internal.http.pipeline.stages.AsyncExecutionFailureExceptionReportingStage.lambda$execute$0(AsyncExecutionFailureExceptionReportingStage.java:51) [info] at java.base/java.util.concurrent.CompletableFuture.uniHandle(CompletableFuture.java:930) [info] at java.base/java.util.concurrent.CompletableFuture$UniHandle.tryFire(CompletableFuture.java:907) [info] at java.base/java.util.concurrent.CompletableFuture.postComplete(CompletableFuture.java:506) [info] at java.base/java.util.concurrent.CompletableFuture.completeExceptionally(CompletableFuture.java:2088) [info] at software.amazon.awssdk.utils.CompletableFutureUtils.lambda$forwardExceptionTo$0(CompletableFutureUtils.java:74) [info] at java.base/java.util.concurrent.CompletableFuture.uniWhenComplete(CompletableFuture.java:859) [info] at java.base/java.util.concurrent.CompletableFuture$UniWhenComplete.tryFire(CompletableFuture.java:837) [info] at java.base/java.util.concurrent.CompletableFuture.postComplete(CompletableFuture.java:506) [info] at java.base/java.util.concurrent.CompletableFuture.completeExceptionally(CompletableFuture.java:2088) [info] at software.amazon.awssdk.core.internal.http.pipeline.stages.AsyncRetryableStage$RetryingExecutor.maybeAttemptExecute(AsyncRetryableStage.java:85) [info] at software.amazon.awssdk.core.internal.http.pipeline.stages.AsyncRetryableStage$RetryingExecutor.maybeRetryExecute(AsyncRetryableStage.java:144) [info] at software.amazon.awssdk.core.internal.http.pipeline.stages.AsyncRetryableStage$RetryingExecutor.lambda$attemptExecute$1(AsyncRetryableStage.java:133) [info] at java.base/java.util.concurrent.CompletableFuture.uniWhenComplete(CompletableFuture.java:859) [info] at java.base/java.util.concurrent.CompletableFuture$UniWhenComplete.tryFire(CompletableFuture.java:837) [info] at java.base/java.util.concurrent.CompletableFuture.postComplete(CompletableFuture.java:506) [info] at java.base/java.util.concurrent.CompletableFuture.complete(CompletableFuture.java:2073) [info] at software.amazon.awssdk.core.internal.http.pipeline.stages.MakeAsyncHttpRequestStage.lambda$executeHttpRequest$1(MakeAsyncHttpRequestStage.java:167) [info] at java.base/java.util.concurrent.CompletableFuture.uniWhenComplete(CompletableFuture.java:859) [info] at java.base/java.util.concurrent.CompletableFuture$UniWhenComplete.tryFire(CompletableFuture.java:837) [info] at java.base/java.util.concurrent.CompletableFuture$Completion.run(CompletableFuture.java:478) [info] at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) [info] at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) [info] at java.base/java.lang.Thread.run(Thread.java:834) [info] Caused by: software.amazon.awssdk.services.sqs.model.SqsException: null (Service: Sqs, Status Code: 500, Request ID: null) [info] at software.amazon.awssdk.services.sqs.model.SqsException$BuilderImpl.build(SqsException.java:95) [info] at software.amazon.awssdk.services.sqs.model.SqsException$BuilderImpl.build(SqsException.java:55) [info] at software.amazon.awssdk.protocols.query.internal.unmarshall.AwsXmlErrorUnmarshaller.unmarshall(AwsXmlErrorUnmarshaller.java:97) [info] at software.amazon.awssdk.protocols.query.unmarshall.AwsXmlErrorProtocolUnmarshaller.handle(AwsXmlErrorProtocolUnmarshaller.java:102) [info] at software.amazon.awssdk.protocols.query.unmarshall.AwsXmlErrorProtocolUnmarshaller.handle(AwsXmlErrorProtocolUnmarshaller.java:82) [info] at software.amazon.awssdk.core.internal.http.async.AsyncResponseHandler.lambda$prepare$0(AsyncResponseHandler.java:88) [info] at java.base/java.util.concurrent.CompletableFuture$UniCompose.tryFire(CompletableFuture.java:1072) [info] at java.base/java.util.concurrent.CompletableFuture.postComplete(CompletableFuture.java:506) [info] at java.base/java.util.concurrent.CompletableFuture.complete(CompletableFuture.java:2073) [info] at software.amazon.awssdk.core.internal.http.async.AsyncResponseHandler$BaosSubscriber.onComplete(AsyncResponseHandler.java:129) [info] at akka.stream.impl.ReactiveStreamsCompliance$.tryOnComplete(ReactiveStreamsCompliance.scala:114) [info] at akka.stream.impl.fusing.ActorGraphInterpreter$ActorOutputBoundary.complete(ActorGraphInterpreter.scala:390) [info] at akka.stream.impl.fusing.ActorGraphInterpreter$ActorOutputBoundary.onUpstreamFinish(ActorGraphInterpreter.scala:416) [info] at akka.stream.impl.fusing.GraphInterpreter.processEvent(GraphInterpreter.scala:523) [info] at akka.stream.impl.fusing.GraphInterpreter.execute(GraphInterpreter.scala:390) [info] at akka.stream.impl.fusing.GraphInterpreterShell.runBatch(ActorGraphInterpreter.scala:625) [info] at akka.stream.impl.fusing.GraphInterpreterShell$AsyncInput.execute(ActorGraphInterpreter.scala:502) [info] at akka.stream.impl.fusing.GraphInterpreterShell.processEvent(ActorGraphInterpreter.scala:600) [info] at akka.stream.impl.fusing.ActorGraphInterpreter.akka$stream$impl$fusing$ActorGraphInterpreter$$processEvent(ActorGraphInterpreter.scala:769) [info] at akka.stream.impl.fusing.ActorGraphInterpreter$$anonfun$receive$1.applyOrElse(ActorGraphInterpreter.scala:784) [info] at akka.actor.Actor.aroundReceive(Actor.scala:537) [info] at akka.actor.Actor.aroundReceive$(Actor.scala:535) [info] at akka.stream.impl.fusing.ActorGraphInterpreter.aroundReceive(ActorGraphInterpreter.scala:691) [info] at akka.actor.ActorCell.receiveMessage(ActorCell.scala:577) [info] at akka.actor.ActorCell.invoke(ActorCell.scala:547) [info] at akka.dispatch.Mailbox.processMailbox(Mailbox.scala:270) [info] at akka.dispatch.Mailbox.run(Mailbox.scala:231) [info] at akka.dispatch.Mailbox.exec(Mailbox.scala:243) [info] at java.base/java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:290) [info] at java.base/java.util.concurrent.ForkJoinPool$WorkQueue.topLevelExec(ForkJoinPool.java:1020) [info] at java.base/java.util.concurrent.ForkJoinPool.scan(ForkJoinPool.java:1656) [info] at java.base/java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1594) [info] at java.base/java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:177)



from Recent Questions - Stack Overflow https://ift.tt/3pzxrtu
https://ift.tt/eA8V8J

Passing in the key and returning the object javascript

With a JSON array structured like this one,

"object1": {
  "key1": "value1"
  "key2": "value2"
}
"object2": {
  "key3": null
  "key4": null
}
}

Could I pass in the key eg. key3 and get returned the object it is part of eg. object2?

I know this would be possible with a for loop, but I have a lot of keys so I am wondering if there is another way.

Thanks



from Recent Questions - Stack Overflow https://ift.tt/2WYPKMk
https://ift.tt/eA8V8J

How do I set a variable inside of an onComplete method?

currently I am trying to pass a value to String variables inside of an onComplete() method. But, when I tried to use it outside of the method, it passes nothing.

Here's my onComplete code:

docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
        @Override
        public void onComplete(@NonNull Task<DocumentSnapshot> task) {
            if(task.isSuccessful()){
                DocumentSnapshot document = task.getResult();
                if(document.exists()){

                    Log.d(TAG,"User full name: " + document.getString("FullName"));
                    Log.d(TAG, "User email: " + document.getString("Email"));
                    donorFullName = document.getString("FullName");
                    donorEmail = document.getString("Email");
                    Log.d(TAG, "donorFullName set: " + donorFullName);
                    Log.d(TAG, "donorEmail set: " + donorEmail);

                }
            }
        }
    });

And here's me trying to use it outside of onComplete:

    BookingInformation bookingInformation = new BookingInformation();
    Log.d(TAG, "donorFullName bookingInformation: " + donorFullName);
    Log.d(TAG, "donorEmail bookingInformation: " + donorEmail);
    bookingInformation.setDonorName(donorFullName);
    bookingInformation.setDonorEmail(donorEmail);

Here's my logcat:

enter image description here



from Recent Questions - Stack Overflow https://ift.tt/3aVqlvp
https://ift.tt/37Xwaq5

TimeoutError returned while connecting via ssh while using splitcopy

I usually use splitcopy to copy contents that are usually large from my server to the router. They work fine on all setups excepts for one setup where I get the following error:

/usr/local/lib/python3.5/dist-packages/paramiko/transport.py:33: CryptographyDeprecationWarning: Python 3.5 support will be dropped in the next release ofcryptography. Please upgrade your Python.
from cryptography.hazmat.backends import default_backend
skipping publickey ssh auth as root != andy
root@andy's password:
ssh authentication succeeded
TimeoutError returned while connecting via ssh:

What can be the possible reasons that I am running into this issue?



from Recent Questions - Stack Overflow https://ift.tt/3aUUZVr
https://ift.tt/eA8V8J

JS convert Array of Objects into JSON GroupBy Format

I'm trying to find a way to convert the following array of objects into JSON

Original Format

const arr = [
  {
    userid: '1000080542',
    photoname: '2c8a4709-ed7e-00a50-0da4ead1de55118-f3-1473281639’,
    datetime: ‘2020-01-24T20:46:05+11:00’
  },
  {
    userid: '1000081532',
    photoname: '73321038-c8bf-57c6e-5d803cd0a920e9a-95-1487447082',
    datetime: ‘2020-01-24T20:46:05+11:00’
  },
  {
    userid: '1000081532',
    photoname: '5c00bc65-db1b-7a394-dd65b462b9e75e2-c5-1487447019',
    datetime: ‘2020-01-24T20:46:05+11:00’
  },
  {
    userid: '1000081532',
    photoname: '986ee1e2-2f8e-bf070-0d70d2e67537835-e2-1473821119',
    datetime: ‘2020-01-24T20:46:05+11:00’
  },
  {
    userid: '1000081532',
    photoname: '09f7cde6-68c8-f462d-c01f7713a2c747f-eb-1474294185',
    datetime: ‘2020-01-24T20:46:05+11:00’
  }
]

Converted Format

{
            1000080542: {
                '2c8a4709-ed7e-00a50-0da4ead1de55118-f3-1473281639': '2020-01-24T20:46:05+11:00',
                '73321038-c8bf-57c6e-5d803cd0a920e9a-95-1487447082': '2020-01-24T20:46:05+11:00'
            },
            1000081532: {
                '5c00bc65-db1b-7a394-dd65b462b9e75e2-c5-1487447019'': '2020-01-24T20:46:05+11:00',
                '986ee1e2-2f8e-bf070-0d70d2e67537835-e2-1473821119': '2020-01-24T20:46:05+11:00',
                '09f7cde6-68c8-f462d-c01f7713a2c747f-eb-1474294185': '2020-01-24T20:46:05+11:00'
            }
        }

I've been trying along these lines but I'm a big off

obj = arr.reduce((h, y) => {
  Object.keys(y).forEach(k => {
    if (!h[k]) {
      h[k] = []
      h[k].push(y[k])
    } else if (!h[k].includes(y[k])) h[k].push(y[k])
  })
  return h
}, {})
console.log(obj)

thanks



from Recent Questions - Stack Overflow https://ift.tt/3mYNhMt
https://ift.tt/eA8V8J

Studying if/else vs if/if statement

I was trying to write a code where all the 0s will be moved to the right of the array. I just used a left and a right pointer.

 public class Solution {
      public int[] moveZero(int[] array) {
        // Write your solution here
        if (array.length==0) {
          return array;
        }
        int left=0;
        int right=array.length-1;
        while (left<=right) {
          if (array[left]!=0) {
            left+=1;
          } 
          if (array[right]==0) {
            right-=1;
          } else {
            int temp = array[left];
            array[left] = array[right];
            array[right] = temp;
            left+=1;
            right-=1;
          }
        }
        return array; 
      }
    }

I know here I should use the if/else if instead of if/if, that's why I have the index out of the bound error. But I don't understand why? If I have the if/if statement, what's the difference does that make rather than using if/else if in this question?



from Recent Questions - Stack Overflow https://ift.tt/3aZEszF
https://ift.tt/eA8V8J

How do I resize my inputs depending on the screen size (chosen by the user in the popup)

const sheets = document.getElementById('sheets');

const siteDocument = document.getElementsByTagName('body')[0];

const amountOfColumns = 2;

const amountOfRows = undefined;

for (var i = 0; i < amountOfColumns; i++) {
  const myNewElement = document.createElement('input');
  myNewElement.width = siteDocument
  sheets.appendChild(myNewElement)
}
for (var x = 0; x < amountOfRows; x++) {

}
#titletext {
  font-size: 5vh;
}
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>repl.it</title>
    <link href="style.css" rel="stylesheet" type="text/css" />
  </head>
  <body>
    <div id="popup"></div>
    <h1 id="titletext">Excel Sheets</h1>
    <div id="buttons"></div>
    <div id="sheets"></div>
    <script src="script.js"></script>
  </body>
</html>

My questions:

  1. How do I get it so the width the element created depends on the width of the screen your using (the user chooses amount of inputs rows and columns), I want to make it responsive and in case there is a bunch of inputs I want to make it so it fits on the screen without having to use the scroll bar (because it's a big pain and I want to code something actually good...)

  2. (You don't have to answer this question) Is vh (view-height) good for responsive web design?

UPDATE:

I want an equation that let's me have ALL the columns and rows on the screen, if I had say 10 columns it should all be on the screen (NOTE: The reason an equation is needed is because I want the columns and rows to be choosen by the user(Is this a bad approach? I'm not sure how I would do it without that)



from Recent Questions - Stack Overflow https://ift.tt/3pzKlro
https://ift.tt/eA8V8J

TypeError: Object(...) is not a function after refactoring from class to function component

I just refactored a legacy React 16.6.3 app from having a class-based SearchBar component to a function component like so:

import React, { useState } from 'react';

const SearchBar = ({ onFormSubmit }) => {
  const [term, setTerm] = useState('');

  const onSubmit = (event) => {
    event.preventDefault();

    onFormSubmit(term);
  };

  return (
    <div className="search-bar ui segment">
      <form onSubmit={onSubmit} className="ui form">
        <div className="field">
          <label>Video Search</label>
          <input
            type="text"
            value={term}
            onChange={(event) => setTerm(event.target.value)}
          />
        </div>
      </form>
    </div>
  );
};

export default SearchBar;

I do not see anything wrong with my code, it should work as expected even if I have yet to refactor the App component from class to function component. I am importing the SearchBar like so:

import React from "react";
import SearchBar from "./SearchBar";
import youtube from "../apis/youtube";
import VideoList from "./VideoList";
import VideoDetail from "./VideoDetail";

class App extends React.Component {
  state = { videos: [], selectedVideo: null };

  componentDidMount() {
    this.onTermSubmit("JavaScript");
  }

What gives here, I cannot detect where I made the error. Here is the exact error:

TypeError: Object(...) is not a function
SearchBar
src/components/SearchBar.js:3
  1 | import React, { useState } from 'react';
  2 | 
> 3 | const SearchBar = ({ onFormSubmit }) => {
  4 |   const [term, setTerm] = useState('');
  5 | 
  6 |   const onSubmit = (event) => {
View compiled
▶ 22 stack frames were collapsed.
Module../src/index.js
src/index.js:5
  2 | import ReactDOM from 'react-dom';
  3 | import App from './components/App';
  4 | 
> 5 | ReactDOM.render(<App />, document.querySelector('#root'));
  6 | 
View compiled


from Recent Questions - Stack Overflow https://ift.tt/3rJm1Fc
https://ift.tt/eA8V8J

having trouble with functions

I need a hand on this, not being able to solve it has been bothering me a lot. Here is my code:

def build_profile(first, last, **user_info): 
    """Build a user's profile dictionary."""  
    profile = {'first': first, 'last': last}

    for key, value in user_info.items():
        profile[key] = value
    return profile

user_0 = build_profile('albert', 'einstein',
        location='princeton')
user_1 = build_profile('marie', 'curie',
        location='paris', field='chemistry')
print(user_0)
print(user_1)
print('\n')

def new_member(name, age, **extra_info):
  """Build a new member's profile"""
  portfolio = {'name': name, 'age': age}

  for key, value in extra_info.items():
    portfolio[key] = value
    return portfolio

member_1 = new_member('vinny geladro', '24', location='alabama')
member_2 = new_member('sally jackson', '28', location='florida', field='biology')
print(member_1)
print(member_2)

I'm new to programming and I have been practicing functions at the moment. The first function (build_profile) is a provided example I found. the second function (new_member) was the one that I wrote to try it out myself.

this is what they both output:

{'first': 'albert', 'last': 'einstein', 'location': 'princeton'}
{'first': 'marie', 'last': 'curie', 'location': 'paris', 'field': 'chemistry'}


{'name': 'vinny geladro', 'age': '24', 'location': 'alabama'}
{'name': 'sally jackson', 'age': '28', 'location': 'florida'}

My issue is that the example function returns both "location" and "field" for Marie Curie, but my function won't return both "location" and "field" for Sally Jackson and I wrote the code practically identical to the example. I'm not sure what I'm doing wrong I've tried rewriting it four different times with different variable names to no avail. I would greatly appreciate the feedback.



from Recent Questions - Stack Overflow https://ift.tt/3n1NzSS
https://ift.tt/eA8V8J

The SMTP server requires a secure connection or the client was not authenticated. Help me please

I want to send an email from my application to verify the email that I used to register but getting this error.

The SMTP server requires a secure connection or the client was not authenticated. The server response 
was: 5.7.57 SMTP; 

I tried going into my Gmail settings and allow less secure apps On but it still doesn't work.

UserController.cs

[NonAction]
    public void SendVerificaitonLinkEmail(string email, string activationCode, string emailFor = "VerifyAccount")
    {
        var verifyUrl = "/User/" + emailFor + "/" + activationCode;
        var link = Request.Url.AbsoluteUri.Replace(Request.Url.PathAndQuery, verifyUrl);

        var fromEmail = new MailAddress("dotnetawesome@gmail.com", "Dotnet Awesome");
        var toEmail = new MailAddress(email);
        var fromEmailPassword = "**********"; // Replace with actual password

        string subject = "";
        string body = "";
        if (emailFor == "VerifyAccount")
        {
            subject = "Your account is successfully created!";

            body = "<br/><br/>We are excited to tell you that your Rockstar Awesome account is" +
                " successfully created. Please click on the below link to verify your account" +
                " <br/><br/><a href ='" + link + "'>" + link + "</a> ";
        }
        else if (emailFor == "ResetPassword")
        {
            subject = "Reset Password";
            body = "Hi, <br/><br/> We got request for reset your account password. Please click on the link below to reset your password." +
                "<br/><br/><a href = " + link + ">Reset Password link </a>";
        }



        SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
        {
            client.EnableSsl = true;
            client.DeliveryMethod = SmtpDeliveryMethod.Network;
            client.UseDefaultCredentials = false;
            client.Credentials = new NetworkCredential(fromEmail.Address, fromEmailPassword);
        };

        using (var message = new MailMessage(fromEmail, toEmail)
        {
            Subject = subject,
            Body = body,
            IsBodyHtml = true
        })
            client.Send(message); // 
    }


from Recent Questions - Stack Overflow https://ift.tt/3o6EQ36
https://ift.tt/eA8V8J

JPA JPQL nested select statement

I have a very simple join table relating two tables, to simplify the problem we can say table1 is A and table 2 is B, with a join table AB.

A AB B
A_id AB_id B_id
A_details A_id_fk B_details
B_id_fk

where A_id_fk and B_id_fk are foreign keys respectively. Im trying to create a query to retrieve all rows of A that have a relation to B. So my function receives B_id as an argument, and I want to search AB to get all rows where B_id_fk == b_id, and then use search A for all rows where A_id == the A_id_fk returned from previous search.

I tested and it can be done in plain SQL using nested select like this:

SELECT * 
FROM A 
WHERE A_ID = 
   (SELECT A_id_fk 
   from AB 
   where B_id_fk = B_id);

So i read the documentation for JPQL: http://openjpa.apache.org/builds/1.2.0/apache-openjpa-1.2.0/docs/manual/jpa_langref.html#jpa_langref_exists and tried this

@Transactional
    public List<A> getA(int B_id){
        TypedQuery<A> query = em.createQuery("select i from A i where i.A_id = 
            (select z.A_id_fk from AB z where z.B_id_fk = :B_ID)", A.class);
        return query.setParameter("B_ID",B_id).getResultList();
    }

Im really lost right now because i followed the given example in the documentation, But its giving me unable to resolve z.A_id.fk errors, is there maybe a way to do B.class nested within A.class? Im not sure what im supposed to do here.



from Recent Questions - Stack Overflow https://ift.tt/3n83yyY
https://ift.tt/eA8V8J

Is there a bug in the DateTime.Parse method when UTC is used with time zone offsets?

The Microsoft documentation states that, among other string representations of DateTime structures, DateTime.Parse(string) conforms to ISO 8601 and accepts Coordinated Universal Time (UTC) formats for time zone offsets.

When I run the following unit test cases, DateTime.Parse(string) and DateTime.TryParse(string, out DateTime) accepts an additional character at the end of the source string. This seems to be a bug. When more than one additional character is appended, the method correctly fails to parse the string.

[Theory]
[InlineData("2020-5-7T09:37:00.0000000-07:00")]
[InlineData("2020-5-7T09:37:00.0000000-07:00x")]
[InlineData("2020-5-7T09:37:00.0000000-07:00xx")]
[InlineData("2020-5-7T09:37:00.0000000Z")]
[InlineData("2020-5-7T09:37:00.0000000Zx")]
public void TestParse(string source)
{
    DateTime dt = DateTime.Parse(source);
    Assert.True(dt != null);
    bool b = DateTime.TryParse(source, out dt);
    Assert.True(b);
}

This unit test case was written to simplify my code and illustrate the behavior I am seeing (I recognize that expected failures should be handled differently).

Tests 1 and 2 pass and the 3rd test (with the "xx" suffix) fails. It seems to me that the second test (with the "x" suffix) should fail.

When no time zone designator is provided, test 4 passes and test 5 fails. This seems to be correct behavior.

I'm wondering if anyone has encountered this, and if so, is there general agreement that this is a bug?



from Recent Questions - Stack Overflow https://ift.tt/3o3OT8X
https://ift.tt/eA8V8J

How to validate user input while running a while with those values

I'm writing a password generator that asks the user to enter a password LENGHT and generates it that long (it works)

Problem: I do validate user input (while/try/except), it gets the Value Error right, it gets the minimum length right BUT it does not take the maximum value and generates always the SAME password with the length PLUS the new length.

Maybe some examples will help

from random import randint

lowerCase = "abcdefghijklmnopqrstuvwxyz"
upperCase = lowerCase.upper()
numbers = "1234567890"
special = "!#$%&/()=?¡@[]_<>,."

password_creation = lowerCase + upperCase + numbers + special

password = ""
lenght = 0
while True
    try:
        password_lenght = int(input("How many characters do you wish the password? Minimum 8 maximum 1024: "))
        if password_lenght < 8 or password_lenght > 1024:
            print("Minimun 8 characters - maximum 1024, try again")
    except ValueError:
        print ("Please enter a valid NUMBER...")
        continue
    else:
        while lenght < password_lenght:



        password = password + password_creation[randint(0, len(password_creation) -1)]
        lenght +=1
              
    
        print("Generated password: ", password)
    

if I run this code it kind of works:

>>> %Run z_strong_password_gen.py
How many characters do you wish the password? Minimum 8 maximum 1024: asdsads
Please enter a valid NUMBER...

ok, it detects if I enter non-numerical values,

now let's try a number below 8 (the minimum.

How many characters do you wish the password? Minimum 8 maximum 1024: 1
Minimun 8 characters - maximum 1024, try again
Generated password:  $
How many characters do you wish the password? Minimum 8 maximum 1024: 3
Minimun 8 characters - maximum 1024, try again
Generated password:  $?$)

ok, it goes with the message "Minimun 8 characters - maximum 1024, try again" BUT it calculates the password

now let's try with the maximum

How many characters do you wish the password? Minimum 8 maximum 1024: 1030
Minimun 8 characters - maximum 1024, try again
Generated password:  $?$NDcB&vMDY&IX@¡x#hLxP8u!oa_F6PGg&DQV8WBOwkqJW@VJ8nmFA$wrF]7soN<C(J[x#[HRm,xL(7(OiCcdV43#XUfa9o7LYwBq55[n24geBl=@U<&!$fH]01&>]bG3/l&[>u2mA4N9IiNUUTj=tWJ)g4wz>A67qNV7O]aKZVfvc3F?B/TCsCjzYe3pOQ%f1nrvFO7prBr[C_Eqs8W?7GU/vor/>xJtV.FLKUL94)KZ(JCc1#gFv,=wJ5rvBR2[5)hhv[tAi)&8AXB1n)FPyUi6WZeqzWnj@R0t.WYja%r2pD_3¡hoW7nRncdf,ExV5._)W(/P3yOyvp#jZNpQIt6Y1cbfoq[mweSp#f)¡ADNz_Duibe<U9pJD4]4x,/G51fORryfVaekX=PIes?T>KTvfy>sQMgNjZ]4M,=5vD!G%,/gYZn(J_pxJlKzjUE65VJn)ZRVpI!&dHDtK(vh=IN=p4i7#E¡4[r!.$]J@>4&HQqSq?DXyvis<Gs)@$=5I/SRGV2&¡]DU0P$=CF,hoj7@]KhPLWsWrFgC@nEU8i3jC3yZKt)_r=m?@KH<sA$D#,f_2%rV$gwzMZoyxh=b[kBD5N%k<1SEpc<f93.)9eh74D6oi)XkylTNA3O%Vq)eUpF9VA$H5)NYUBHihMW.$O#ytgb!24?WLzi>piF0T(!6V#l1141v@i%]_BxCV2uPEPdajOdxqkJs#Fq,zAa#T.%DE%D%,I<y4zY5lgBcua!,LBu1jHf%4waKujW.Y&WMpnf<qa%#sCZlGm17iNu9fRLXXAdO[1s@g4?ZhTL60Blg?PtZNJw<AB>$poCK¡cJ7ON$kXAEZ/c¡X/H]FCHhjCVUm#na¡p_o>]7Bp//rr3YJFj<OpCL2kg,,XEsC0¡<i/$HP#Bc!X#nMlRVMW8NdV7x7ru_(2OW6/Q1P¡c_ZmJz<Z<7zELz¡6yp00$ZD&sErhSz81mVU$oO(rtqAYs=p3h%lbTr$EWiJxvq)X<z909k18rN07ZRfq@C7hWRyTH1!?&PR3%@?
How many characters do you wish the password? Minimum 8 maximum 1024: 

It raises the message that the number is bigger than 1024 BUT it calculates the password again

And if I do calculate a password, let's say, 10 characters..it does ok, if I want to calculate another one of...20, it takes the first 10 from the previous calculation and just add 10 more to fill the 20 (maybe I have to clear or delelte the varaiable)

check the example

How many characters do you wish the password? Minimum 8 maximum 1024: 10
Generated password:  **fOweHv%Wm,**
How many characters do you wish the password? Minimum 8 maximum 1024: 20
Generated password:  **fOweHv%Wm,**p6AEoh8L)l
How many characters do you wish the password? Minimum 8 maximum 1024:


from Recent Questions - Stack Overflow https://ift.tt/37YT68j
https://ift.tt/eA8V8J

Listen to back button in mobile browser and e.preventDefault() then use our separate function in react function

I am working on a react web app add want to preventDefault back button to my function in react function

for exact code use check -https://github.com/rishabhjainfinal/react-expence-calculator/blob/main/src/App.js

yes I can use react routing but I wanna test this way first

function App() {
    
     function onBack(){
        if (CP === "Month"){
            UpdateCP("Year")
        }
        else if (CP === "Day"){
            UpdateCP("Month")
        }        
    }    
    
    //some event listener function to prevent to go back 

    switch (CP){
        case 'Day':
            return (<Day date={AD} CP={CP} UpdateCP={UpdateCP}/>)
        case 'Year':
            return (<Year monthNames={monthNames} CP={CP} UpdateCP={UpdateCP} UpdateAM={UpdateAM} Save_in_excel={Save_in_excel}/>)
        default :
            return (<Month month={AM} CP={CP} UpdateCP={UpdateCP} UpdateAD={UpdateAD} AM={AM} AY={AY} monthNames={monthNames} />)
    }
}

This is my first react app and want to do it this way only.

Yes, there are many different ways but none of then is working:

  • 'https://ift.tt/3b0pNnI'
  • 'https://ift.tt/2KP0tGC'
  • 'https://ift.tt/38OKIYa'

the more detailed description -> supposed you created a react P.W.App of single-page but you wanna change the components every time back button is pressed like mobile back button or browser back button, and this is only possible by listening to the press of the back-button and prevent default case and run my own function this takes 2 steps:-

  1. listen to the event
  2. run function

try using

const [finishStatus, setfinishStatus] = useState(false);

    useEffect(() => {
        const onBackButtonEvent = (e) => {
            console.log('kdfjlsdjfds')
            e.preventDefault();
            if (!finishStatus) {
                if (window.confirm("Do you want to go back ?")) {
                    setfinishStatus(true)
                    // your logic
                    // props.history.push("/");
                } else {
                    window.history.pushState(null, null, window.location.pathname);
                    setfinishStatus(false)
                }
            }
        }
    
        window.history.pushState(null, null, window.location.pathname);
        window.addEventListener('popstate', onBackButtonEvent);
        return () => {
            window.removeEventListener('popstate', onBackButtonEvent);  
        };
    });

this code does nothing in my app (no effect at all) for of componentDidMount and componentDidUnMount in useEffect hook, our whole page is a single component when it Unmounts page unloads 😥



from Recent Questions - Stack Overflow https://ift.tt/3pArNY8
https://ift.tt/eA8V8J

PHP remove empty tring from array

I'm trying to remove all empty strings "" from the kat-array. I tried to do it by using array_filter function like this:

$array = array_filter($array, "strlen");

The problem is that kat[4] is now an object instead of an array.

Any idea how I can remove empty stings from an array without transforming them into an object?

Before

enter image description here

After

enter image description here



from Recent Questions - Stack Overflow https://ift.tt/3nZ1gDw
https://ift.tt/38RNdJk

2020-12-30

SQS long polling and retention policy

I have two questions regarding SQS which I couldn't find answers to.

  1. Seems like polling in the AWS console is always Long Polling, although the queue is set to short polling. It always polls for 30 seconds even when the Receive message wait time is set to 0. Is this possible or I didn't get it?
  2. When I have a DLQ connected to the standard queue and the retention period of the queue is over, will the message get to the DLQ or just disappear? When trying it, seems like the message disappears but I want to be sure that's the expected behavior.


from Recent Questions - Stack Overflow https://ift.tt/34Xbz3s
https://ift.tt/eA8V8J

Move all versions of a given file in a S3 bucket from one folder to another folder

I have set up an S3 bucket with versioning enabled.

One external process is writing the json files, (each json file corresponds to a single Student entity) to the S3 bucket.

I have decided the S3 bucket folder structure as follows:

 s3://student-data/new/ <-- THIS WILL CONTAIN ALL THE UNPROCESSED JSON FILES
 s3://student-data/processed/ <-- THIS WILL CONTAIN ALL THE PROCESSED JSON FILES.

Now, I have a Cron that runs periodically, once at every 6 hours.

New JSON files are written to new folder by external process.

I would like the Cron to process all the JSON files with associated versions in new folder and after processing is over, move all the files with all existing versions in new folder to processed folder.

Here I am able to fetch the current version for a json file written to new folder and move this to processed folder post processing.

But I am not getting an idea regarding how can I move a file with all its versions from new to processed so that in the future I don't have to process same version of a file twice.



from Recent Questions - Stack Overflow https://ift.tt/3mY4Nka
https://ift.tt/eA8V8J

how to make responsive table with bootstrap

need help to make table responsive.

On this size everything is ok: enter image description here

but when screen size is reduced im getting smth like this: enter image description here

table is displayed on col-md-7:

<div class="row">
                    <div class="col-md-7">
                        <div class="ritekhela-fancy-title-two">
                            <h2>TurnyrinÄ— lentelÄ—</h2>
                        </div>

                        <div class="rs-point-table sec-spacer">
                            <div class="tab-content">
                                <table>
                                    <tr>
                                        <td>Vieta</td>
                                        <td class="team-name">Komanda</td>
                                        <td>Sužaista</td>
                                        <td>Perg.</td>
                                        <td>Lyg.</td>
                                        <td>Laim.</td>
                                        <td>Įm.</td>
                                        <td>Pr.</td>
                                        <td>+/-</td>
                                        <td>Taškai</td>
                                    </tr>
                                    <tr>
                                        <td>01</td>
                                        <td class="team-name">Banani FC</td>
                                        <td>60</td>
                                        <td>35</td>
                                        <td>08</td>
                                        <td>16</td>
                                        <td>02</td>
                                        <td>04</td>
                                        <td>11</td>
                                        <td>95</td>
                                    </tr>
                                   </table>
                            </div>
                        </div>
                    </div>

EDITED: If i trying to add max and min width, marked place is reducing too much: enter image description here



from Recent Questions - Stack Overflow https://ift.tt/3pA16Te
https://ift.tt/3pA17qg

Cannot get Query elements on razor page

I have two query-selection on my page one for customers and one for suppliers. Why do I not see any elements?

== c# code ==

c# code of page

Pic of VS19 with debugger

in debugger elements are shown see pic number 2

== in Razor Page==

Pic of HTML Code

Unfortunately I cannot see any items. Any Ideas?

Layout of page

Attached you get my code sorry for only posting pictures

My c# Code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Mvc.Rendering;
using WorkCollaboration.Data;
using WorkCollaboration.Models;

namespace WorkCollaboration.Pages.Contacts
{ 
    public class CreateModel : PageModel
    {
        private readonly WorkCollaboration.Data.WorkCollaborationContext _context;

        public CreateModel(WorkCollaboration.Data.WorkCollaborationContext context)
        {
            _context = context;
        }

    public async Task<IActionResult> OnGetAsync()
        {
            CustomerDropDownDisp = await _context.CustomerDropDown.ToListAsync();  // Added for DropDown
            SupplierDropDownDisp = await _context.SupplierDropDown.ToListAsync();  // Added for DropDown
            return Page();
        }

        [BindProperty]
        public Contact Contact { get; set; }
        public DayOfWeek DayOfWeek { get; set; }
        public IEnumerable<CustomerDropDown> CustomerDropDownDisp { get; set; }
        public IEnumerable<SupplierDropDown> SupplierDropDownDisp { get; set; }

        // To protect from overposting attacks, enable the specific properties you want to bind to, for
        // more details, see https://aka.ms/RazorPagesCRUD.
        public async Task<IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return Page();
            }

            _context.Contact.Add(Contact);
            await _context.SaveChangesAsync();

            return RedirectToPage("/ContactsOverview/Index");
        }
    }
}

Here my Razor Page Html

@page 
@model WorkCollaboration.Pages.Contacts.CreateModel

@{
    ViewData["Title"] = "Create";
    ViewData["RandomId"] = Guid.NewGuid().GetHashCode();
}

<h1>Create</h1>
<h4>Contact</h4>
<p>
    <a asp-page="/ContactsOverview/Index">Back to Index</a>
</p>
<hr />
<div class="row">
    <div class="col-md-4">
        <form method="post">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="Contact.ContactId" class="control-label"></label>
                <input asp-for="Contact.ContactId" value='@ViewData["RandomId"]' readonly="readonly" class="form-control" />
                <span asp-validation-for="Contact.ContactId" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Contact.LastName" class="control-label"></label>
                <input asp-for="Contact.LastName" class="form-control" />
                <span asp-validation-for="Contact.LastName" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Contact.FirstName" class="control-label"></label>
                <input asp-for="Contact.FirstName" class="form-control" />
                <span asp-validation-for="Contact.FirstName" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Contact.CustomerId" class="control-label"></label>
                <input asp-for="Contact.CustomerId" class="form-control" />
                <span asp-validation-for="Contact.CustomerId" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Contact.CustomerId" class="control-label"></label>
                <select id="CusId" aps-items="@(new SelectList(Model.CustomerDropDownDisp,"CusId","CusName"))">
                    <option value="" selected disabled> -- Select Customer--</option>>
                </select>
                <span asp-validation-for="Contact.CustomerId" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Contact.SupplierId" class="control-label"></label>
                <input asp-for="Contact.SupplierId" class="form-control" />
                <span asp-validation-for="Contact.SupplierId" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Contact.SupplierId" class="control-label"></label>
                <select id="SupId" aps-items="@(new SelectList(Model.SupplierDropDownDisp,"SupId","SupName"))">
                    <option value="" selected disabled> -- Select Supplier--</option>>
                </select>
                <span asp-validation-for="Contact.SupplierId" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Contact.PrivateStreet" class="control-label"></label>
                <input asp-for="Contact.PrivateStreet" class="form-control" />
                <span asp-validation-for="Contact.PrivateStreet" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Contact.PrivateStreetNo" class="control-label"></label>
                <input asp-for="Contact.PrivateStreetNo" class="form-control" />
                <span asp-validation-for="Contact.PrivateStreetNo" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Contact.PrivateStreetAdditionalInfo" class="control-label"></label>
                <input asp-for="Contact.PrivateStreetAdditionalInfo" class="form-control" />
                <span asp-validation-for="Contact.PrivateStreetAdditionalInfo" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Contact.PrivateZip" class="control-label"></label>
                <input asp-for="Contact.PrivateZip" class="form-control" />
                <span asp-validation-for="Contact.PrivateZip" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Contact.PrivateTown" class="control-label"></label>
                <input asp-for="Contact.PrivateTown" class="form-control" />
                <span asp-validation-for="Contact.PrivateTown" class="text-danger"></span>
            </div>
            <div class="form-group">
                @Html.LabelFor(model => model.Contact.PrivateCountry, htmlAttributes: new { @class = "form-group" })
                <div class="form-group">
                    @Html.DropDownListFor(model => model.Contact.PrivateCountry, new List<SelectListItem>
                    {
                        new SelectListItem {Text = "CH", Value = "CH", Selected = true },
                        new SelectListItem {Text = "D", Value = "D" },
                        new SelectListItem {Text = "FL", Value = "FL" },
                    }, new { @class = "form-control" })
                    @Html.ValidationMessageFor(model => model.Contact.PrivateCountry, "", new { @class = "text-danger" })
                </div>
            </div>
            <div class="form-group">
                <label asp-for="Contact.PrivatePhone" class="control-label"></label>
                <input asp-for="Contact.PrivatePhone" class="form-control" />
                <span asp-validation-for="Contact.PrivatePhone" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Contact.BusinessPhone" class="control-label"></label>
                <input asp-for="Contact.BusinessPhone" class="form-control" />
                <span asp-validation-for="Contact.BusinessPhone" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Contact.MobilePhone" class="control-label"></label>
                <input asp-for="Contact.MobilePhone" class="form-control" />
                <span asp-validation-for="Contact.MobilePhone" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Contact.Mail" class="control-label"></label>
                <input asp-for="Contact.Mail" class="form-control" />
                <span asp-validation-for="Contact.Mail" class="text-danger"></span>
            </div>
            <select asp-for="DayOfWeek" asp-items="Html.GetEnumSelectList<DayOfWeek>()">
                <option value="">Choose a day</option>
            </select>
            <div class="form-group">
                <input type="submit" value="Create" class="btn btn-primary" />
                <a href="/ContactsOverview/Index" class="btn btn-primary">Back to List</a>
            </div>
        </form>
    </div>
</div>


from Recent Questions - Stack Overflow https://ift.tt/2KMCojJ
https://ift.tt/eA8V8J

How do I replace a value in one cell based on value in another cell?

function CopyinData_AM_A() {
/* Edit the vars below this line for your needs */
var sourceSheet  = "Students AM" ;  // Enter the name of the sheet with the source data
var sourceRange = "B7:N77" ; // Enter the range of the cells with the source data
var targetSheet = "Students AM A" ; // Enter the name of the target sheet
var targetRange = "B7:N77" ; // Enter the range of cells you wish to copy data to. Note this must be same size as source range.
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName(sourceSheet);
var values = sheet.getRange(sourceRange).getValues();
ss.getSheetByName(targetSheet).getRange(targetRange).setValues(values);
}

How would I add this into the above script? The action needs to occur after the data is copied into the sheet. I am only a VB coder. 'Students AM A' is a formula free sheet.

      For each cell in ‘Students AM A'!N7:N77 then
              If Ncell= ‘Menu!D14' then Hcell = ”O"
              Check next cell
      End

I'd have zero issue doing this in VB, I just started using google scripts about 3 months ago. Anyone recommend a good book to assist me in learning this google script stuff?



from Recent Questions - Stack Overflow https://ift.tt/3rDU5Th
https://ift.tt/eA8V8J

Microsoft sql sever + c# - save not working

private void button4_Click(object sender, EventArgs e)
    {
        try
        {
            // first table
            SqlConnection cn = new SqlConnection(@"Data Source = DESKTOP - MO4HHVS; Initial Catalog = MechanicProject; Integrated Security = True");
            cn.Open();
            string dateoftheday = dateTimePicker1.Value.Year + "-" + dateTimePicker1.Value.Month + "-" + dateTimePicker1.Value.Day;
            SqlCommand cmd = new SqlCommand("insert into Clients (Imie,Nazwisko,Adres,Nr_rejstracji,Nr_telefonu,Marka_samochodu,Data,Rok,Moc_silnika,nr_VIN,Przebieg,Rzeczy_uszkodzone,Rzeczy_naprawione,Komentarz,Podsumowanie_ceny) values('" + textBox1.Text+"','"+ textBox63.Text + "','" + textBox3.Text + "','" + textBox2.Text + "','"+textBox5.Text+"','"+textBox4.Text+"','"+dateoftheday +"','"+textBox7.Text+"','"+textBox6.Text+"','"+textBox10.Text+"','"+textBox8.Text+"','"+textBox12.Text+"','"+textBox11.Text+"','"+textBox13.Text+ "','" + textBox62.Text + "')", cn); 
           int result= cmd.ExecuteNonQuery();
            if(result==1)
            {
                //second table
                SqlCommand cmd1 = new SqlCommand("select max(id) from Clients", cn);
                string refid = cmd1.ExecuteScalar().ToString();
                for(int i=0;i<dataGridView1.Rows.Count-1;i++)
                {
                    string itemname = dataGridView1[0, i].Value.ToString();
                    string qty = dataGridView1[1, i].Value.ToString();
                    string rate = dataGridView1[2, i].Value.ToString();
                    string totalprice = dataGridView1[3, i].Value.ToString();
                    SqlCommand cmdx = new SqlCommand("insert into Clients (Ref_ID,Nazwa_czesci,Ilosc,Cena,Cena_za_wszystko) values('" + refid+"','"+itemname+"','"+qty+"','"+rate+"','"+totalprice+"')", cn);
                    cmdx.ExecuteNonQuery();
                }

                MessageBox.Show("Profil zapisany!","Save",MessageBoxButtons.OK,MessageBoxIcon.Information);
                
                cn.Close();
            }

            
        }
        catch (Exception) { }
    }

Table has name 'dbo.Clients'

SELECT TOP (1000) [id]
  ,[Imie]
  ,[Nazwisko]
  ,[Adres]
  ,[Nr_rejstracji]
  ,[Nr_telefonu]
  ,[Marka_samochodu]
  ,[Data]
  ,[Rok]
  ,[Moc_silnika]
  ,[nr_VIN]
  ,[Przebieg]
  ,[Rzeczy_naprawione]
  ,[Podsumowanie_ceny]

FROM [MechanicProject].[dbo].[Clients]

Another table is 'Table'

SELECT TOP (1000) [id]
  ,[Imie]
  ,[Nazwisko]
  ,[Adres]
  ,[Nr_rejstracji]
  ,[Nr_telefonu]
  ,[Marka_samochodu]
  ,[Data]
  ,[Rok]
  ,[Moc_silnika]
  ,[nr_VIN]
  ,[Przebieg]
  ,[Rzeczy_naprawione]
  ,[Podsumowanie_ceny]

FROM [MechanicProject].[dbo].[Clients]

Does anybody know how to fix my issue? Data in the textBox should be stored in two tables. I have no idea why it doesn't work. Earlier, however, after replacing the computer, I lost the database. I guess I did everything as I did then. I have made new connections, etc. Thank you in advance for your help.



from Recent Questions - Stack Overflow https://ift.tt/2WT6eWv
https://ift.tt/eA8V8J

Find the same part in two different view images

I have two images from two cameras like below.

camera 1

camera 2

How can I find the overlapping view of two cameras and mark the overlapping views in two images? Thank you for any suggestions.



from Recent Questions - Stack Overflow https://ift.tt/37YAdCM
https://ift.tt/eA8V8J

Slick Slider covers up elements below

My slick slider images are covering up the elements that are supposed to sit below, and I'm not sure why. I need #features to sit below #slideshow, but right now it's covered up. I'm not sure what's making the slider overlap the elements below it on the page. I don't want to just "push" the #features div down with CSS, like by using bottom: -50px or whatever because I'm aiming for responsive design. I need the slideshow slider and slides to take up the same amount of height that the images do. Hopefully this makes sense! Here's my code:

HTML:

<div id="slideshow">
    <div class="slide"><img src="images/Need Space.jpg"></div>
    <div class="slide"><img src="images/Open Lot.jpg"></div>
    <div class="slide"><img src="images/IMG_0713a.jpg"></div>
    <div class="slide"><img src="images/IMG_0714a.jpg"></div>
</div>
<div id="features" class="flex">
    <div>Safe</div>
    <div>Secure</div>
    <div>24-Hour Access</div>
</div>
<div id="description">
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
</div>

CSS:

    /* SLIDESHOW */
#slideshow {
  width: 100%;
  height: 50vh;
  margin-bottom: 5vh;
}

.slide {
  width: 100%;
  height: 100%;
}

.slide img {
  width: 100%;
}

.slick-initialized .slick-track {
    display: flex;
    align-items: center;
}

/* FEATURES */
#features div {
  margin: 5vw;
  padding-bottom: .5vh;
  font-weight: bolder;
  font-size: 2.5vh;
  letter-spacing: .25vw;
  border-bottom: 1px solid white;
}


from Recent Questions - Stack Overflow https://ift.tt/3mUvmXr
https://ift.tt/eA8V8J

How do you watch a callable object's arguments and return values?

I have a Python object and I want to know what args, kwargs, and return values it made. The solution should be something like this.


class Fizz(object):
    def do_something(self, item, blah=8):
        return "done"


buzz = Fizz()

with watch(buzz.do_something) as container:
    buzz.do_something("asdf")
    buzz.do_something("another", blah=10)

container  # [(("asdf", ), dict(), "done"), (("another", ), {"blah": 10}, "done")]

So the key points are

  • Able to watch args, kwargs, and return values
  • Is temporary (I can decide when and how to watch and when to un-watch)
  • Ideally, this should work with instance objects. But at minimum, it needs to be able to at least work with class, method, and function definitions (like how mock.patch does it).

Similar Things That Already Exist

mock.patch allows you to watch arguments but, as far as I know, it replaces the class / function / method. The original callable object does not get called, which is not what I want. I want the original to still be called while also keeping track of what's passed in and out of the callable object.

Maybe there's a way to make mock do what I need it to do or some other existing library? Anyone know of anything?



from Recent Questions - Stack Overflow https://ift.tt/3mWUgFJ
https://ift.tt/eA8V8J

How can I combinate two MySQL queries and sort them?

I have 3 tables: Parts, Store and Delivery

store.id
store.mainpnid = parts.id
store.mainpn
store.subid 
store.bnsn
store.class
store.expire
store.status
store.station

delivery.id
delivery.mainpnid
delivery.mainpn
delivery.subid
delivery.bnsn
delivery.class
delivery.expire
delivery.status
delivery.to
delivery.statindlvr

parts.metctrl
parts.description
parts.id
parts.class

I have two queries until now:

SELECT store.id, store.mainpnid, store.mainpn, store.subid, store.bnsn, store.class, store.expire, store.status, store.station, parts.metctrl, parts.description, parts.id, parts.class FROM store INNER JOIN parts ON store.mainpnid=parts.id WHERE (store.status='SA' OR store.status='US' OR store.status='QRT') AND parts.metctrl='yes' AND (parts.class = 'TR' OR parts.class = 'T') ORDER BY store.mainpn ASC, store.bnsn ASC

and

SELECT delivery.id, delivery.mainpnid, delivery.mainpn, delivery.subid, delivery.deliveryn, delivery.bnsn, delivery.class, delivery.expire, delivery.status, delivery.statindlvr, delivery.to, parts.metctrl, parts.description, parts.id, parts.class FROM delivery INNER JOIN parts ON delivery.mainpnid=parts.id WHERE (delivery.status='SA' OR delivery.status='US' OR delivery.status='QRT') AND (delivery.statindlvr = 'transit' OR delivery.statindlvr = 'pending' OR delivery.statindlvr = 'ready') AND parts.metctrl='yes' AND (parts.class = 'TR' OR parts.class = 'T') ORDER BY delivery.mainpn ASC, delivery.bnsn ASC

Until now its works ok but now I have to make a new query who content results from store and results from delivery and sort all of results mainpn ASC and bnsn ASC is there any way to do this?



from Recent Questions - Stack Overflow https://ift.tt/3rCngWQ
https://ift.tt/eA8V8J

ProgressBar with loaded percentage when Glide image is loading

I'm trying to show a progress bar with the currently loaded percentage of the image, like 1% - 50% - ...

I looked it up a lot, every answer is just to show a simple ProgressBar with setVisibility without showing loaded percentage.

I tried AsyncTask, but the progress doesn't change.

Thanks



from Recent Questions - Stack Overflow https://ift.tt/34U8b9z
https://ift.tt/eA8V8J

Why cant i delete a local Git branch in IntelliJ?

So Im new to Git, and to test i have created the local Branch "test". But for some reason, I can not delete it, just the master branch. I just dont have the option to do that, but there is not a single person on the internet that asked the same question, see here



from Recent Questions - Stack Overflow https://ift.tt/3pwI5Bc
https://ift.tt/3o2K1Ru

In Python, How can i compare two similar 'QRcode'?

I recently got two QRcode, and these seem similar. But i'm novice in python. How can i compare in number(like 'indentical 100%', 'similarity 97%')

Thank you.



from Recent Questions - Stack Overflow https://ift.tt/2WXh8KC
https://ift.tt/eA8V8J

Simple question about slicing and for loops without indices

If I was making this loop:

for i in range(len(array)):
  for j in range(len(array)+1):
    # some code using array[i] and array[j]

Would there be a way to do the same thing in this format?

for element in array:
  for next_element in array:
    # some code using element and next_element

Or would I just be better off using the i, j format?



from Recent Questions - Stack Overflow https://ift.tt/34Uz0dB
https://ift.tt/eA8V8J

Why is data undefined from json?

I want to get the names of the cocktails through api. I brought the data. But I can't read the properties inside.

This is JSON

{
  "drinks": [
    {
      "idDrink": "12784",
      "strDrink": "Thai Iced Coffee",
      "strCategory": "Coffee / Tea",
      "strIBA": null,
      "strAlcoholic": "Non alcoholic",
      "strGlass": "Highball glass",
      "strDrinkThumb": "https://www.thecocktaildb.com/images/media/drink/rqpypv1441245650.jpg",
      "strIngredient1": "Coffee",
      "strIngredient2": "Sugar",
      "strIngredient3": "Cream",
      "strIngredient4": "Cardamom",
      "strMeasure1": "black",
      "strMeasure3": " pods\n",
      "strImageAttribution": null,
      "strCreativeCommonsConfirmed": "No",
      "dateModified": "2015-09-03 03:00:50"
    }
  ]
}

This is useFetch.jsx This file serves as a data import.

import { useState, useEffect } from "react";

function useFetch(url) {
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(true);
  async function fetchUrl() {
    const response = await fetch(url);
    const json = await response.json();
    setData(json);
    setLoading(false);
  }
  useEffect(() => {
    fetchUrl();
  });
  return [data, loading];
}
export default useFetch;

This is Main.jsx This file displays the data on the screen.

import React from "react";
import styled from "styled-components";
import useFetch from "./useFetch";

const url = "https://www.thecocktaildb.com/api/json/v1/1/random.php";
const Main = () => {
  const [data, loading] = useFetch(url);
  return (
    <>
      {loading ? (
        "Loading..."
      ) : (
        <ul>
          {[data].map(
            ({ idDrink, strDrink, strAlcoholic, strGlass, strDrinkThumb }) => (
              <Container>
                <img src={`${strDrinkThumb}`} alt="" />
                <li key={`${data.idDrink}`}>{`Drink ${data.strDrink}`}</li>
              </Container>
            )
          )}
        </ul>
      )}
    </>
  );
};
export default Main;
const Container = styled.div``;

Run console.log([data]); and I can see that the data is flowing well. But the data in is undefined.



from Recent Questions - Stack Overflow https://ift.tt/3nZ93AV
https://ift.tt/eA8V8J

Trying to figure out how to combine two queries for a subreport

I'm trying to update an Access database to be easier to maintain and update. To anonymize the data, I altered the data to use food ordering as a metaphor/analog. My experience with Access is not exactly basic, but very much learning to solve issues as I've come across them. So I don't know how close, or how far off, I am currently.

A Google Sheet I'll be referencing: https://docs.google.com/spreadsheets/d/1UYt1SKbBrKqE6IWCTyUHVNV89jGfy4KoHWTzCXtO0CM/edit?usp=sharing

NOTE: In response to GMP's comment I tried to convert the information into this post directly.

Goal

How it started was each "order" was a single row in a table. There are 20 some near identical reports with minor differences that hard coded values based on the "product". The primary goal is to remove the hard coded per report data. In the end combining the "generic" and "order specific" certificate of analysis like data into a report. I've been trying to make this a subreport that I can drop into the 20 odd some reports until I can figure out how to prune that mess.

The goal, though open to better solutions, is sketched out in "Example Report".

https://i.imgur.com/t2tjPSb.png (Not enough karma to be allowed to embed an image yet, table-fied version below)

Category Grouping: Spec_Category
Spec Order Specific Value General Analysis Value
[Expr1001] and [Spec_Specification] [Query_Order_Specific]![Order_AnalysisValue] [Query_Generic_Analysis]![Spec_Analysis]
[Expr1001] and [Spec_Specification] [Query_Order_Specific]![Order_AnalysisValue] [Query_Generic_Analysis]![Spec_Analysis]
Category Grouping: Spec_Category
Spec Order Specific Value General Analysis Value
[Expr1001] and [Spec_Specification] [Query_Order_Specific]![Order_AnalysisValue] [Query_Generic_Analysis]![Spec_Analysis]
[Expr1001] and [Spec_Specification] [Query_Order_Specific]![Order_AnalysisValue] [Query_Generic_Analysis]![Spec_Analysis]

What is done so far

General Data

I have the subreport working for the most recent general COA information. This is "Certificate of Analysis" data that is supposed to be the most recent value per Spec and Product pairing.

The format of this data is the "Query_Generic_Analysis" tab in the Google Sheets. It is working fine by itself. These would be columns A and D of the "Example Report".

Spec_ProdType Spec_Category Spec_Specification Spec_Analysis
Fries Condiment Mustard 0.1045
Fries Condiment Pepper 0.0397
Fries Condiment Citrus 0.1886
Fries Condiment Tears 0.5445
Fries Condiment Ketchup 0.0835
Fries Physical Description Red Color 1.5 Max
Fries Physical Description Flavor Bland
Fries Texture Free Fatty Acid (FFA) Oleic 0.05% Max
Fries Texture Salt 95 mg/l
Fries Texture Moisture 0.10% Max
Fries Texture Vegemite 42 ML/KG
Milkshake Condiment Mustard 0.1045
Milkshake Condiment Pepper 0.0397
Milkshake Condiment Citrus 0.1886
Milkshake Condiment Tears 0.5445
Milkshake Condiment Ketchup 0.0835
Milkshake Physical Description Red Color 6.0 Max
Milkshake Physical Description Flavor Bland
Milkshake Texture Free Fatty Acid (FFA) Oleic 0.10% Max
Milkshake Texture Salt 95 mg/l
Milkshake Texture Moisture 0.10% Max
Milkshake Texture Vegemite 42 ML/KG
Nuggets Condiment Mustard 0.1045
Nuggets Condiment Citrus 0.1886
Nuggets Condiment Tears 0.5445
Nuggets Condiment Ketchup 0.0835
Nuggets Physical Description Red Color 1.5 Max
Nuggets Physical Description Flavor Bland
Nuggets Texture Free Fatty Acid (FFA) Oleic 0.05% Max
Nuggets Texture Salt 95 mg/l
Nuggets Texture Moisture 0.10% Max
Nuggets Texture Vegemite 42 ML/KG
Salad Condiment Mustard 0.076
Salad Condiment Pepper 0.033
Salad Condiment Citrus 0.755
Salad Condiment Tears 0.104
Salad Condiment Ketchup 0.022
Salad Physical Description Red Color 1.5 Max
Salad Physical Description Flavor Bland
Salad Texture Salt 10 mg/l
Salad Texture Vegemite 42 ML/KG
Tofu Condiment Mustard 0.076
Tofu Condiment Pepper 0.033
Tofu Condiment Citrus 0.755
Tofu Condiment Tears 0.104
Tofu Condiment Ketchup 0.022
Tofu Physical Description Red Color 1.5 Max
Tofu Physical Description Flavor Bland
Tofu Texture Free Fatty Acid (FFA) Oleic 0.05% Max
Tofu Texture Salt 10 mg/l
Tofu Texture Vegemite 42 ML/KG
Watermelon Condiment Citrus 0.1886
Watermelon Condiment Ketchup 0.0835
Watermelon Condiment Mustard 0.1045
Watermelon Condiment Pepper 0.0397
Watermelon Condiment Tears 0.5445
Watermelon Physical Description Red Color 1.5 Max
Watermelon Physical Description Flavor Bland
Watermelon Texture Free Fatty Acid (FFA) Oleic 0.05% Max
Watermelon Texture Moisture 0.10% Max
Watermelon Texture Non-GMO attributes 99.1% or better
Watermelon Texture Salt 95 mg/l
Watermelon Texture Vegemite 42 ML/KG

Order Specific Data

Using a Union Query, I've been able to get the order specific COA information. "Query_Order_Specific" is an example of how the query results currently look.

tabKey Order_Specification Order_AnalysisValue Order_Product Order_Category
8986 Mustard 2.8 Watermelon Condiment
8977 Mustard 2.8 Watermelon Condiment
8960 Mustard 2.8 Watermelon Condiment
8952 Mustard 2.8 Watermelon Condiment
8914 Mustard 2.8 Watermelon Condiment
8911 Mustard 2.79 Watermelon Condiment
8562 Mustard 3.14 Watermelon Condiment
8560 Mustard 3.14 Watermelon Condiment
8526 Mustard 3.14 Watermelon Condiment
643 Ketchup 0 Watermelon Condiment
642 Ketchup 0 Watermelon Condiment
611 Ketchup 0 Watermelon Condiment
135 Ketchup 0 Watermelon Condiment
105 Ketchup 0 Watermelon Condiment
84 Ketchup 0 Watermelon Condiment
83 Ketchup 0 Watermelon Condiment
642 Salt 0.03 Watermelon Texture
8627 Salt 0.06 Milkshake Texture
8625 Salt 0.03 Milkshake Texture
524 Ketchup 0.07 Nuggets Condiment
498 Ketchup 0.07 Nuggets Condiment
491 Ketchup 0.07 Nuggets Condiment
474 Ketchup 0.07 Nuggets Condiment
463 Ketchup 0.07 Nuggets Condiment
459 Ketchup 0.07 Nuggets Condiment
458 Ketchup 0.07 Nuggets Condiment
8626 Salt 0 Fries Texture
8624 Salt 0 Fries Texture

The Current Roadblock

The roadblock I'm currently having trouble figuring out is combining these two query sets. I can, and have, created two independent sub reports for each data set. So far, my attempts at joining the two queries in a larger query seem to only give one of two results:

  • The Greater Query is entirely empty
  • The Greater Query only returns results where both the Generic and Order_Specific analysis have values for the specification.

Looking at the "Example Report - With Pseudo Data", there are some specs that have generic data without order specific fata.

https://i.imgur.com/MYvoVgN.png I don't have enough karma to be allowed to embed an image yet, so a crude table conversion below

Table Key: 642
Product: Watermelon
Condiment
Spec Order Specific Value General Analysis Value
Citrus 0.1886
Ketchup 0 0.0835
Mustard 0.1045
Pepper 0.0397
Tears 0.5445
Physical Description
Spec Order Specific Value General Analysis Value
Red Color 1.5 Max
Flavor Bland
Texture
Spec Order Specific Value General Analysis Value
Free Fatty Acid (FFA) Oleic 0.05% Max
Moisture 0.10% Max
Non-GMO attributes 99.1% or better
Salt 0.03 95 mg/l
Vegemite 42 ML/KG

EDITS

  1. Attempted to include the data into the post itself.


from Recent Questions - Stack Overflow https://ift.tt/34RU58k
https://ift.tt/eA8V8J

2D array size problem loading from csv file

int main()
{

    auto base_dir = fs::current_path();
    auto dataset_1 = data_names_1;
    auto dataset_name = base_dir / "NAimg_20101026_145727.csv";

    //double data[10][3];
    std::ifstream file(dataset_name);

    matrix<DataType> data_length;
    file >> data_length;
    
    auto pre_num_row = data_length.nc();
    static const int num_row = 73;//data_length.nr();
    static const int num_column = 74496; //data_length.nc();

    std::cout << num_row << "\n";
    std::cout << num_column << "\n";

    double data[73][74496];

    for (int row = 0; row < 73; ++row)
    {
        std::string line;
        std::getline(file, line);
        if (!file.good())
            break;

        std::stringstream iss(line);

        for (int col = 0; col < 74496; ++col)
        {
            std::string val;
            std::getline(iss, val, ',');
            if (!iss.good())
                break;

            std::stringstream convertor(val);
            convertor >> data[row][col];
        }
    }

    std::cout << data[1][1] << "\n";
  
}

Hello, My name is Q. I want to read a csv file (here the name of the file is NAimg_20101026_145727.csv) and load the data to data array. The size of row and column of the file is 73 and 74496. Therefore, I need double data[73][74496] array. It makes error. When I make a small array, for example, double data[10][20], there is no error. Do you know what is the problem?

I have one more issue. I want to read the size of row and column from csv file and automatically decide the size of double data[row][column]. Therefore, I tried to use data_length.nc(); to decide the row and column of the double data size. Do you know how to decide the size of double data[row][column] from csv file? Thanks



from Recent Questions - Stack Overflow https://ift.tt/2WRAq48
https://ift.tt/eA8V8J